views:

44

answers:

4

I´m trying to set a cell of type "System.Int32" in a DataSet by code, and my try looks like this:

int aCarID = 5; // as an example...

// points out the row that I want to manipulate - I guess this is what doesn´t work???
int insertIndex = myDataSet.tableCars.Rows.Count 

myDataSet.tableCars.Rows[insertIndex]["CarID"] = aCarID;

What happens is: I get an exception of "System.IndexOutOfRangeException".

You´re allowed to say that I´m stupid as long as you provide an answer...

UPDATE!

Yes, I´m trying to create a new row, that´s true - that´s why I´m not using "-1".

So what´s the syntax to create a new row?

If I use tableCars.Rows.Add(...) I need to supply a "DataRow Row" to the Add-function, and I don´t have one to provide - yet! (Catch 22)

NEW UPDATE! Ooops, found it - "NewRow()" :-)

+2  A: 

You do realize that indices start with zero in C#? That means if your table has 3 rows, you're trying to access the 4th row because insertIndex = 3. Try insertIndex - 1.

Edit: Since you're trying to add a new row and already found out how to do so, also don't forget to save those changes to the database (I assume that's what you want to do). The most simple way is to set the UpdateCommand-property of the DataAdapter you used to fill the DataSet (or actually the DataTable in the DataSet). You can also have the update commands generated, using a subclass of the DbCommandBuilder.

Christian
Your "Edit:" saved me a couple of minutes, thanks!
Jack Johnstone
+1  A: 

From MSDN:

An IndexOutOfRangeException exception is thrown when an attempt is made to access an element of an array or collection with an index that is outside the bounds of the array or less than zero.

so the problem is when you use a wrong index as Christian said.

Rox
A: 

try to create new row first, because you want to access row which doesn't exists, or you have to insert your information into row indexed (insertIndex - 1). Datarow indexes first position is 0, as in arrays.

scatterbraiin
A: 

You're using a strong-typed dataset, but your insert code is actually for a non-strongly typed dataset.

The following code will work for you (and is much easier!)

var insertRow = myDataSet.tableCars.NewtableCarsRow();
insertRow.CarID = aCarID;
myDataSet.AcceptChanges();

That's it!

NOTE: this code works from .NET version 3.5 onwards. For prior versions, replace the var keyword with tableCarsRow (I'm assuming that you didn't customize the default name for the datarow in the DataSet designer).

code4life