Looping over DataRow to compare current row data and previous row data - c#

I need to iterate over a DataRow in gridview, to compare the values from the current row and previous row. Appreciate if someone could help on this issue. I'm new
I am currently iterating like this, but i dont know how to continue:
//Check if current row ACTIVITY = LOAD_A and previous row ACTIVITY = LOAD_B is true , then store the
value and do the sum calculation.
foreach (DataRow sda in dt.Rows)
{
if (sda.Field<string>("ACTIVITY") == "LOAD_A")
{
}
}

As devNull already mentioned you can use a variable to hold the value of the previous iteration of the foreach loop.
This could look like this:
DataRow previousDr = null;
foreach (DataRow sda in dt.Rows)
{
if (previousDr != null)
{
if (sda.Field<string>("ACTIVITY") == "LOAD_A" &&
previousDr.Field<string>("ACTIVITY") == "LOAD_B")
{
//Store value und do calculation.
}
}
previousDr = sda;
}

You can use for statement and indexer property of DataRow to accomplish this
DataColumn column = table.Columns["ACTIVITY"];
for (int index = 1; index < table.Rows.Count; ++index)
{
if (table.Rows[index - 1].Field<string>(column) == "LOAD_B" && // previous row
table.Rows[index].Field<string>(column) == "LOAD_A") // current row
{
// do somthing
}
}

Related

How to increment a variable if it is the first row of data table

i have a data table having several rows. I want to increment a variable say i, only if it is the first row of the data table. How can I do that?
foreach (DataRow row in dt.Rows)
{
address = (row["address"].ToString());
Counter += 1;
int count = Convert.ToInt16(Dt.Rows[i]["limit"]);
//for the first row
if (Counter == count)
{
i += 1;
}
// also if it is the last row
exit;
You should work with a for loop - hat makes the index access easier
for (int i = 0; i < dt.Rows.Count; i++)
{
string address = dt.Rows[i].Field<string>("address");
if (i == 0)
{
//first row, increment here
}
if (i == dt.Rows.Count - 1)
{
//last row
}
}
Why not a simple flag, say isFirstRow?
bool isFirstRow = true;
foreach (DataRow row in dt.Rows)
{
if (isFirstRow)
{
isFirstRow = false;
//TODO: Increment here
}
...
Edit: In case of last row we can do postprocessing:
DataRow lastRow = null;
foreach (DataRow row in dt.Rows) {
// Candidate for the last row
lastRow = row;
...
}
if (lastRow != null) {
//TODO: Put relevant code for the last row
}
You can use code like below. Use IndexOf method of DataRowCollection class to determine if it's the first row. I have created a sample DataTable object before the loop. The main part of this answer is the if statement within the loop's body that checks for row index.
Keep in mind that the index of row in DataTable starts from 0 and not 1. So, first row has an index of 0, second row has an index of 1, third row row has index of 2 and so on.
DataTable dt = new DataTable();
dt.Columns.Add("EmployeeId", typeof(int));
dt.Columns.Add("FirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
dt.Columns.Add("Grade", typeof(int));
// Here we add five DataRows.
dt.Rows.Add(11, "John", "Smith", 9);
dt.Rows.Add(92, "Sunita", "Mali", 7);
dt.Rows.Add(2, "Anil", "Kumar", 4);
dt.Rows.Add(5, "Mike", "Reb", 11);
dt.Rows.Add(1, "Sunil", "Dev", 12);
//your counter variable
int i= 0;
foreach(DataRow row in dt.Rows) {
//use IndexOf method to check if it's the first row
if( dt.Rows.IndexOf(row) == 0) {
i++;//only first row causes increment of i
}
if(dt.Rows.IndexOf(row) == (dt.Rows.Count -1)) {
//its the last row of datatable
}
}

How to declare datarow outside foreach loop?

I am using foreach loop and inside that loop I declared datarow
DataSet ds = Business.Site.GetSiteActiveModulesWithStatus(siteId);
foreach (DataRow dr in ds.Tables[0].Rows)
How can I implement this datarow outside foreach loop and how can I use for loop instead of foreach loop?
To loop in a for:
for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//To acess the row
DataRow row = ds.Tables[0].Rows[i];
}
Outside the for, to acess a specific DataRow you can do like this:
//Change 0 to other numbers to acess other rows
DataRow row = ds.Tables[0].Rows[0];
To access the row variable outside of the loop, you simple have to declare it outside:
DataRow rowFound = null;
for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
var currentRow = ds.Tables[0].Rows[i];
if(true /*To do: define some matching criteria*/)
{
rowFound = currentRow;
}
}
if(rowFound != null)
{
// We found some matching, what shall we do?
}
But you could write the same also in a LINQish style:
var rowFound = ds.Tables[0].AsEnumerable()
.Where(row => true /*To do: define some matching criteria*/)
.FirstOrDefault();
All code in this answer is untested.

Get value of a column and store it into an array - DataGridView

I have the following code:
int countRows = dataGridView3.SelectedRows.Count;
int rowIndex = 0;
foreach (DataGridViewRow row in dataGridView3.SelectedRows)
{
int selectedRowIndex = dataGridView3.SelectedCells[rowIndex].RowIndex;
DataGridViewRow selectedRow = dataGridView3.Rows[selectedRowIndex];
capacity = Convert.ToInt32(selectedRow.Cells["Cust_Number"].Value);
capStore.Add(capacity);
rowIndex++;
}
I try to go through each selected row in my DataGridView and store the value from the column "Cust_Number" into an ArrayList, so that I can change it later. Somehow he just grabs the second row each time I iterate and I have the same value in my ArrayList duplicated. What is wrong here?
I would try the following code :
if(dataGridView3.SelectedRows != null && dataGridView3.SelectedRows.Count > 0)
{
foreach (DataGridViewRow dgvr in dataGridView3.SelectedRows)
{
int tempVal = 0;
if(dgvr.Cells["Cust_Number"].Value != null && int.TryParse(dgvr.Cells["Cust_Number"].Value.ToString(), out tempVal))
{
capStore.Add(tempVal);
}
}
}
This is simpler and safer.

DataRow - How to cancel adding row to datatable?

I have a problem.
I have two loops (one for row, one for column) for creating data in DataTable. I want to check if cell is empty for column named "Name" and if it is empty just don't add this row. And here is a question: How to cancel adding row?
Got some code:
for (int i = 0; i < data.Count(); i++)
{
cell = data.ElementAt(i);
DataRow row;
row = dataTable.NewRow();
foreach (string column in columns)
{
if (row["Name"] == "")
{
row = null;
}
else
{
row[column] = cell;
}
}
if (row != null)
{
dataTable.Rows.Add(row);
}
}
But after next loop is starting it throws NullException: Object reference not set to an instance of an object.
Generally I want to add Rows to DataTable only those where value of cell is not empty at column called "Name" (i mean where is "").
What is the best way or easiest way to do it right?
Change it as:
....
foreach (string column in columns)
{
if (row["Name"] == "")
{
row = null;
break; //--> Add this line
}
else
{
row[column] = cell;
}
}
....

C# DataGridRow.Rows Selects the new row

I have a simple function in my program that selects the current cell, then it (FillsDown) copies the current cell into ALL the cells below it.
However my simple function places the value in the Row at the bottom which is the new row and I do not want the value to be populated here.
Heres the current code. (Where COLINDEX is just the column im referring to in my grid)
string replacestring = row.Cells[COLINDEX].Value.ToString();
foreach (DataGridViewRow row in dataGrid1.Rows)
{
if (row.Index > startrow)
{
row.Cells[COLINDEX].Value = replacestring;
}
}
Is there a simeple method/property I can check against so I dont accidently populate the last row ?
My example below uses a fake property (.Exist)
foreach (DataGridViewRow row in dataGrid1.Rows)
{
if ((row.Index > startrow) && row.Exist)
{
row.Cells[COLINDEX].Value = replacestring;
}
}
DataGridViewRow has a property called IsNewRow
And try to walk the Rows collection using the index
for(int x = startRow + 1; x < dataGrid1.Rows.Count; x++)
{
DataGridViewRow row = dataGrid1.Rows[x];
if (row.IsNewRow == false)
{
row.Cells[COLINDEX].Value = replacestring;
}
}

Categories

Resources