.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

how to loop DataTable.Rows using ForEach activity?

Posted By:      Posted Date: December 04, 2010    Points: 0   Category :Windows Application

How can I use ForEach<T> activity to look each DataRow in DataTable.Rows?

Seems that DataTable.Rows is DataRowCollection, which does not support IEnumerable.


View Complete Post

More Related Resource Links

loop through different sets of rows in a datatable



I have a following scenario - 

A use selects criterias from a webform (C#) - a result is then returned from the sql. Say, to start, there are 2000 data returned from the sql and are stored in a dataset.

Now, the user wants to choose a number of drops (up to 6) - with the number of drops selected, they can enter their own quantity in each box. So, they can divide the 2000 records into 6 different drops. With each drop, there is campaigncode created based on the mail date and the job number they provide. 

So, now i have the 2000 records in a dataset. What i want to do is loop through the gridview where the user fill out the quantity depending on the number of drops (for ex: if they say 3 drops, then there will be 3 rows in gridview with 3 quantity box to fill).

In the loop, I am getting the quantity, dropdate and the job number. The Campaigncode is created as well. Then, i am looping through the datarow in the dataset; updating the Campaign Code column with the CampaignCode for the number of records thats set in a loop. It works but the Campaign Code is not populated for the next set of records.

Here is the code:

private void AddAEFiels()
        int _totalCount = 0;
        string job = null;
        foreach (GridViewRow row in gvDropDates.

foreach activity?

HI, I retrieved data using IdataReader in class file. I want to use that returned IDataReader dr in foreach. In design mode XAML, dragged foreach. Now what is the Type Argument and Values I need to keep in FOREACH Properties?

Error on 23rd Loop of Foreach

Hi, I have a MAster Package callling 8 Dimension Package and 5 fact table packages. Fact table Packages are in for eachloop. They have to loop 24 times during FirstRun Each fact table load more than 500000 rows in every loop, and out of 5, two package loads more than million rows in every loop. I got the following error message when the package was looping for the 23rd time. One of the five Fact table package failed with following error DTS primeoutput failed returned error code 0xC02020C4 SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on component "Staging Table "(1) returned error code 0xC02020C4. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure. After when I ran package explicitly, it ran well Please help on what to be done to avoid this error and what does this error mean?. I am Using SQL Server 2008, i5 Processor, 3.42GB RAm, DefaultBufferMaxRows = 10000 and Default BufferSize 10MB, EngineTHread=10 Thanks, Anuja

ForEach Loop Container Configuration Question

So here is my question/situation. I have a table that contains a list of all of our servers/instances for my organization. I have a script that I'd like to execute against all of the servers in that list and I was thinking that I should be able to use this container to pull the name/instance from the table, execute the script, store the results in a local table. However, I'm not quite sure on how to attack this meaning not sure which configuration that I would need to use to get me going down the right direction. I've looked around and found alot of documentation on how to enumerate multiple files and folders, but nothing really for what I'm trying to do. Any help or direction would be greatly appreciated.Big Ern

SSIS 2005 - Foreach loop container - Stopping the loop after processing X number of file?

I need to stop the Foreach loop container from processing more files in the folder than desired. Scenario:  If I only want 1 files processed, i need to stop the loop after it finds 1 file.  No matter what the contraints or tests or variables I set, the loop processes all the files in the folder.  This is bad because I need the value of the 1st mapped variable and not the last one it finds. I have tried counting records and setting variables used in the contraints but to no avail  Nothing seems to stop the loop. Please advise

How to go to next iteration of ForEach Loop container on task failure

I'm using a ForEach Loop container to iterate through a set of files and import/validate the data.  Within each loop, the first thing that happens is that I fill a variable from a table and then use a script task to make sure that the rest of the package should be run for this particular file.  If it should continue, I set Dts.TaskResult = Dts.Results.Success, and if it shouldn't, I set it to Dts.Results.Failure.  My question is, how do I get it to exit the current iteration of the loop and continue to the next iteration?  The way it is now, the package just stops completely.  I set the FailPackageOnFailure property to False for the script task, but that doesn't make a difference.  I also tried pointing a failure precedence contstraint bacl to the loop container, but that's not allowed.  How can I make it just continue in the loop?   Thanks.

Using Foreach loop Container in SSIS 2005 package and scheduling the package using SQL job on 64-bit

I've an SSIS package 2005 which uses a for each loop container, this package runs fine when I run it on the local machine . My server is 64 bit SQL 2005 and I 've successfully deployed my package on the server both to the File system and SQL server. I've also set Run64bitruntime to false in my pacakge. Now I need schedule the package using SQL job. Since Microsoft Jet Provider 4.0 is not available for 64 bit, I had to write script to schedule the package. Here is my script. declare   @ssisstr varchar(8000) declare @returncode int set   @ssisstr = 'dtexec /sq Package1 /DE 123' EXEC   @returncode = xp_cmdshell @ssisstr select   @returncode I'm getting the following error when I execute the job. Could not load package "Package1" because of error 0xC0010014. Description: One or more error occurred. There should be more specific errors preceding this one that explains the details of the errors. This message is used as a return value from functions that encounter errors. I'm getting the same error if I run this from commandline. Any help would be really appreciated. Thanks in advance. PARC

Foreach Loop Container.ForEachEnumerator.Properties[FileSpec] Exception -This occurs when an attempt

I run into the following 2 exceptions when I execute a package on SQL Server 2005 64 bit machine. The package fails when SQL Server version is 9.0.3310 which is a production box. I have tested it on 3 others development boxes with SQL version 9.0.1399, 9.0.3315 & 9.0.4053 and the package executes fine. I am unable to make a determination if this issue is related to SQL versions or a bug in the package design. I would like to understand the exception better before I request an SP3 & patches installed to upgrade it to version 9.0.4053 on the production box. I have scheduled jobs to run these packages and we are trying to locate Excel files on a drive using For Each Loop Enumerator. The packages are configured to use configuration files. Please note the destination directory does have the Excel files we are looking for. Source: Well_Test_Package Description: The package path referenced an object that cannot be found: "\Package\Daily Alloc Spread Sheet Foreach Loop Container.ForEachEnumerator.Properties[Directory]". This occurs when an attempt is made to resolve a package path to an object that cannot be found.  End Warning  Warning: 2010-08-31 00:41:13.66     Code: 0x80012017     Source: Well_Test_Package      Description: The package path referenced an object that ca

Find rows in one DataTable from another DataTable and remove them

Hi!I'm sure this is a ridiculously newbie question, but I'm having a lot of trouble with it and have spent hours wrestling and Googling this problem so I'm finally going to ask for help.I have a DataTable of available time slots.  I have another DataTable of reserved time slots.  I need to remove from the list of available slots the ones that have been reserved.  The blocks are in 15 minute increments, but one of my problems is that the reservation can be longer than 15 minutes.  I've had some luck removing one or two, but not all of the required columns.  Here's my code (it doesn't work right now).  Any help would be greatly appreciated!private void GetAvailableTime() { Common common = new Common(); DataTable copyAvailableTime = AvailableTime(); DataTable availableTime = AvailableTime(); DataTable reservedTime = ReservedTime(); StringBuilder sb = new StringBuilder(); copyAvailableTime.DefaultView.Sort = "startTime"; foreach (DataRow dr in reservedTime.Rows) { copyAvailableTime.DefaultView.RowFilter = string.Format("startTime >= '#{0}#' AND endTime <= #{1}#", dr["StartTime"].ToString(), dr["EndTime"].ToString()); foreach (DataRow dr2 i

Create task activity break out inside a While loop

Hi I have developed a sharepoint state machine workflow. I want to assign a same task to more than one users, but unfortunatly, I cannot give the attribute "AssignTo" to more users in the code, even like this:"this.workflowTask1Properties.AssignedTo = "mydomain\\user01;mydoman\\user02", that will result in an empty value to the attribure.So, I involved the createtask activity in a While loop so I can asign deferent user in each loop, but It's very stange,  the loop always stopped in the second time, does anybody have met this issue?I have referensed Amit's question:http://social.msdn.microsoft.com/forums/en-US/windowsworkflowfoundation/thread/b238978d-f330-420c-823e-b77b0e19414d?prof=requiredbut I have no define the "correlation refernce " in my workflow.my code is here:public SPWorkflowTaskProperties workflowTask1Properties;public int abc;...private void OnWorkflowActivated(object sender, ExternalDataEventArgs e)        {            ...           this.abc = 0;           ...        }...private void CreateTask1(object sender, EventArgs e)        { 

C# Allowing user to select variables to use in a foreach loop

Hi guys, First project, first post. My app builds webpages and personalises the content by running a foreach loop through rows in a dataset. My original web page build was hardcoded and works fine. I want to take this one stage further and allow users to paste their own html into a text box and use button controls to insert values from the dataset arrays.  Doing this however leads to the app writing the string verbatim. Some examples at this point might help:  Original code here System.IO.StreamWriter objWriter; objWriter = new System.IO.StreamWriter(webpage);                     objWriter.WriteLine("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>"); objWriter.WriteLine("<head>"); objWriter.WriteLine("<title>" + row.ItemArray.GetValue(0).ToString() + "'s very own webpage" + "</title>";); objWriter.WriteLine("<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>"); objWriter.WriteLine(""); objWriter.WriteLine("</head>"); objWriter.WriteLine("<body>"); objWriter.WriteLine("<h1>Well hello there " + row.ItemArray.GetValue(5).ToStri

sql Server 2008: duplicated rows in Activity monitor

There are identical notes (Session id, Login etc.) in a Processes tab of Activity Monitor. Usially it is two, sometimes three same rows. Does anyone have a similar situation? Is this a bug or it is just s/th wrong in my comp? (SQL Server 2008 R2 CUP3)

Could not set a datasource to Schema Rowset Enumerator in Foreach Loop Container



Everytime I want set a datasource (also if I create a new one with an click on the drop down) I got the following error message from the container.


TITLE: For each schema rowset

The new connection, LocalHost.ReportServer, is not an OLE DB connection so it can not be used by the schema rowset enumerator and, therefore, will not be added to the connections list.

But if I generate a OLE DB connection manually it does not appear in the dropdown list of the container. Does anybody know what I have to do in that case?

Thanks, Nils

foreach loop and SqlDataAdapter to update WHERE UserId = UserId ?


I'm trying to figure out how to update multiple rows in my Directory table, when a user changes their Street Number or Street Name in their profile.  They can add multiple users to a directory and each user they add to the directory has this primary users UserId in it. So if the primary user changes their address, I want it to update the address for all the users they listed in the directory as well. I'm adding this to the On_Click in the Code Behind, so when they click to update their profile, it fires this function as well.

This code may be way off, but here's what I have right now:

                //Update directory user addresses for this account, if profile address has changed
                if ((currentStreetNumber != creatingStreetNumber) || (currentStreetName != creatingStreetName))
                    string myDirectoryConnection = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                    SqlDataAdapter cmd2 = new SqlDataAdapter("Update Directory SET [StreetNumber] = @StreetNumber, [StreetName = @StreetName] WHERE [UserId] = @UserId", myDirectoryConnection);
                    cmd2.UpdateCommand.Parameters.Add("@UserId", currentUserId.ToString());

Loop through datatable always have problem


Hi I pull data from Database to be in a data table called dtDatatable after which specified that to the gridview.

 ElseIf Not dtTransaction Is Nothing Then

 gvTransaction.DataSource = dtTransaction


For i = 0 To gvTransaction.Rows.Count // I do a loop to loop through the table --> but it always displayed error saying there is no row position at row 2. 


i have used different ways to go around this. but still get the same error.Please assist.. 

Thank you!

SQL-transaction for foreach/for loop


i am making a web application in which at one time i have to insert the vales into three table..

first table will generate scope_identity,

then in foreach loop values are inserted in 2nd table with ref of scope identity

and then same with the 3rd table

problem is i dont know how to put transaction in foreach loop......

please help me.......

here is my dummy code please help me....

SqlConnection con = new SqlConnection("server=xxxx;uid=xxxx;password=xxx;database=xxxx;connect timeout=3600");
        SqlCommand cmd = new SqlCommand("insert into test(a,b,c,d,e,f,g,h) values ('a','b','c','d','e','f','g','h');select scope_identity()", con);
        decimal idd = (decimal)cmd.ExecuteScalar();

        for (int i = 0; i < 15; i++)
            SqlCommand cmd1 = new SqlCommand("insert into test1(a,b,c,d,e,f,g,h) values ('"+idd.ToString()+"','b','c','d','e','f','g','h')", con);
        for (int i = 0; i < 15; i++)
            SqlCommand cmd2 = new SqlCommand("insert into test2(a,b,c,d,e,f,g,h) values ('&

How to convert DataTable objects to IList without using For Each Loop


DataTable result = GetDataSetByQuery(query).Tables[0]
IList<string> li=new IList<string>();

Can we implement through LINQ ?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend