Domanda

Why I get a "there is no row at position 0" exception:

DSGeneral dg = new DSGeneral();

// I create 1 table
DSGeneral.GeneralDataTable t = new DSGeneral.GeneralDataTable();
dg.Tables.Add(t);

// The 1st row
DSGeneral.GeneralRow r = t.NewGeneralRow();
r.Code = "code";
r.Value = "7";
t.Rows.Add(r);

// The 2nd row
DSGeneral.GeneralRow r2 = t.NewGeneralRow();
r2.Code = "exp";
r2.Value = "5";
t.Rows.Add(r2);

It throws here:

int numClave = Convert.ToInt16(dg.General[0].Value);

Furthermore, debugging I could see that my typed dataset dg has 2 tables, I wonder why.

È stato utile?

Soluzione

When you are using strongly typed DataSets, you declare the tables and dataadapters on the designer. The DataTables then are already part of that DataSets, hence you don't need to to add them again to it.

That explains why the dataset contains two tables instead of one. Because of the same reason you get the exception. You have added the rows to your manually created table and not to the declaratively added.

But

 dg.General[0].Rows[0].Value

accesses the auto-generated DataTable which is still empty.

So you just have to use the available table:

DSGeneral dg = new DSGeneral();
DSGeneral.GeneralRow r = dg.General.NewGeneralRow();
r.Code = "code";
r.Value = "7";
dg.General.AddGeneralRow(r);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top