Dot Net Fluke: Getting by on C# for iSeries RPG Developers

Useful tutorials on C# and .NET for RPG iSeries AS/400 developers. Brought to you from the folks at AranRock Consulting

7/30/08

Reading a C# Grid (Reading a subfile)

Previously I discussed how to write records to a C# grid -  the equivalent of an RPG subfile. But how do you read those records? Say you wanted to add totals entered to store in another table?

You might recall that unlike in RPG where we read a table and write each record from the table directly to a subfile, C# creates a layer between the physical data and the grid by using a data set. This is handy because you don't have to worry about updating multiple tables every time an update/add or delete is made to the grid, this is handled automatically when you define what tables belong to the data set.

Here is some code we used before to fill a data set:

// build a command object and prepare an SQL statement so that you can look at your table 


SqlCommand buildData = conn.CreateCommand(); 


cmd.CommandText = "Select * from Orders where OrdQty >100"; 


// Build the Data Adapater - this fills a data set 


SqlDataAdapter dataAdapter = new SqlDataAdapter(buildData); 


// Now create the data set. The data structure which contains the data retrieved by the data adapter 


DataSet orderDataSet = new DataSet(); 


// Populate the dataset with the Data Adapter 


dataAdapter.Fill(dataSet);



 



The data set defined above would be 'bound' to a grid as follows



DataGridView1.DataSource = ds.Tables.Item(0)



Now when the grid is displayed it will display orders from Orders file through the layer of the data set. Any changes made to the grid would be reflected in the data set.



To update the database simply use the adapater's update method



 this.custTableAdapter.Update(ds DataSet);




But back to our original question, how do you read the data in the data set for processing?


In RPG you could read each record in the subfile in a DOW loop, in C# you can use the For Each loop

which can read through data set as follows.


  foreach (DataRow rowx in ds.Tables(0))
{
totalInnings = totalInnings + rowx["Innings"];
}


The foreach statement is a powerful construct and makes processing data extremely simple. The above statement will process all the records in the subfile





and any processing just has to occur in between the curly brackets.









2 Comments:

At August 5, 2008 at 10:23 AM , Anonymous Anonymous said...

I have a dataset and try to read it but I keep getting an 'object not found' error. Any idea on why I would be getting this?

 
At August 5, 2008 at 12:31 PM , Anonymous Anonymous said...

You can actually write directly to a grid from a table - you don't need a dataset.

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home