c# getting item in row from datatable - c#

foreach (DataRow row in dt.Rows)
{
string[] temprow={"","","",row[3].ToString()};
dtworklist.Rows.Add(temprow);
}
dt is my datatable. i need to get the 3rd element in the row and put it into an array. the above is what i tried so far with no luck. how do i do it?

Try this:
int i=0;
List<string> l=new List<string>();
foreach (DataRow row in dt.Rows)
{
l.Add(Convert.ToString(row[2]));
}
string[] stringArray=l.ToArray();

what if you try:
foreach (DataRow row in dt.Rows)
{
DataRow added = dtworklist.NewRow();
int columnOfInterest = 2; // could be the column name as a string too
added[columnOfInterest] = row[columnOfInterest];
}
Note that I have used index of 2 because the first index in the list is zero. If you want the third item you would be interested in index 2.

Related

how to dynamically get a single value from a datatable in C#?

I am new at C#, I have a DataTable named dt; Now I want to get the values from it's each row and a specific column named "Number" from which I can calculate a third column to add. But cant' do it. Any ideas? Please help me.
foreach (DataRow dRow in dt.Rows)
{
int number = dt.Rows[0].Field<int>(1);
dRow[Ratio] = Convert.ToString(((number * 100) / grandTotal)) + " %";
}
Use a loop and the Field method, presuming that Number is an int:
foreach(DataRow row in dt.Rows)
{
int number = row.Field<int>("Number");
// do your calculation
row.SetField("ThirdColumn", someValue);
}

Duplicate data of a ROW of a datagridview into another

I need to REPLICATE a SINGLE row from a datagridview(grid_display) into another datagridview(grid_detail)
I could replicate the column headers.like below.
foreach (DataGridViewColumn c in grid_display.Columns)
{
grid_detail.Columns.Add(c.Clone() as DataGridViewColumn);
}
//then you can copy the rows values one by one (working on the selectedrows collection)
foreach (DataGridViewRow r in grid_display.SelectedRows)
{
int index = grid_detail.Rows.Add(r.Clone() as DataGridViewRow);
foreach (DataGridViewCell o in r.Cells)
{
grid_detail.Rows[index].Cells[o.ColumnIndex].Value = o.Value;
}
}
How do i replicate the DATA of A SINGLE selected row from grid_display to grid_detail ?

Error in datarow,Collection was modified; enumeration operation might not execute [duplicate]

This question already has answers here:
How do I loop through items in a list box and then remove those item?
(8 answers)
Closed 9 years ago.
I have for-each loop in which the data row is updated so the exception ,Collection was modified; enumeration operation might not execute is generated. any way to fix it? i have seen To-List function but it is not working with data row , here is my code:
foreach (DataRow row in dataTable.Rows) {
temp = row[0].ToString();
foreach (DataRow rows in dataTable.Rows) {
if (temp == rows[0].ToString()) {
tempdatatable.Rows.Add(row[0],row[1]);
dataTable.Rows.Remove(rows);
//Update happens here
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
You cannot modify collection while enumerating it using Enumerator, which is happening behind the scene of the foreach statement (MDSN link).
One possible way to solve this problem is to collect rows to be deleted in the first enumeration and than remove them in the separate loop like this:
var rowsToDelete = new List<DataRow>();
foreach (DataRow row in dataTable.Rows)
{
temp = row[0].ToString();
foreach (DataRow rows in dataTable.Rows)
{
if (temp == rows[0].ToString())
{
tempdatatable.Rows.Add(row[0],row[1]);
rowsToDelete.Add(rows);
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
rowsToDelete.ForEach( x => dataTable.Rows.Remove(x) );
You can also replace foreach loop with for, but you need to do extra work properly handling the current index while deleting the elements.
Try this :
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var tempRow = dataTable.Rows[i];
var temp = dataTable.Rows[i][0];
for (int j = 0; j < dataTable.Rows.Count; j++)
{
DataRow rows = dataTable.Rows[j];
if (temp == rows[0].ToString())
{
tempdatatable.Rows.Add(tempRow[0], tempRow[1]);
dataTable.Rows.Remove(rows); //Update happen here
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
I would say that you should make a separate table of entries, and instead of calling datatable.Rows.Remove(rows), add the row "rows" to this other table. Then, whenever row or rows iterates, you run an if statement to check if its been "deleted", i.e., in the list of deleted rows. After the enumeration is over, you can then delete those rows permanently from the table.
EDIT:
Here's the code implementation:
DataTable duplicates = dataTable;
duplicates.Rows.Clear(); /* Produces an empty duplicate of the
dataTable table to put the duplicates in */
foreach (DataRow row in dataTable.Rows)
{
if (!duplicates.Rows.Contains(row))
{
temp = row[0].ToString();
foreach (DataRow rows in dataTable.Rows)
{
if (temp == rows[0].ToString()&&!duplicates.Rows.Contains(rows)) //need unique key
{
tempdatatable.Rows.Add(row[0],row[1]);
}
tempdatatable.DefaultView.Sort = "gscitations DESC";
dataGridView1.DataSource = tempdatatable;
}
}
}
foreach (DataRow row in duplicates.Rows)
{
dataTable.Rows.Remove(row);
}
if you don't have a unique key, you can try switching !duplicates.Rows.Contains(/*specific row*/) for duplicates.Rows.IndexOf(/*specific row*/)>0. That should provide an adequate substitute.

Find a string in all DataTable columns

I am trying to find a fast way to find a string in all datatable columns!
Followed is not working as I want to search within all columns value.
string str = "%whatever%";
foreach (DataRow row in dataTable.Rows)
foreach (DataColumn col in row.ItemArray)
if (row[col].ToString() == str) return true;
You can use LINQ. It wouldn't be any faster, because you still need to look at each cell in case the value is not there, but it will fit in a single line:
return dataTable
.Rows
.Cast<DataRow>()
.Any(r => r.ItemArray.Any(c => c.ToString().Contains("whatever")));
For searching for random text and returning an array of rows with at least one cell that has a case-insensitive match, use this:
var text = "whatever";
return dataTable
.Rows
.Cast<DataRow>()
.Where(r => r.ItemArray.Any(
c => c.ToString().IndexOf(text, StringComparison.OrdinalIgnoreCase) > 0
)).ToArray();
If you want to check every row of every column in your Datatable, try this (it works for me!).
DataTable YourTable = new DataTable();
// Fill your DataTable here with whatever you've got.
foreach (DataRow row in YourTable.Rows)
{
foreach (object item in row.ItemArray)
{
//Do what ya gotta do with that information here!
}
}
Don't forget to typecast object item to whatever you need (string, int etc).
I've stepped through with the debugger and it works a charm. I hope this helps, and good luck!
This can be achieved by filtering. Create a (re-usable) filtering string based on all the columns:
bool UseContains = false;
int colCount = MyDataTable.Columns.Count;
string likeStatement = (UseContains) ? " Like '%{0}%'" : " Like '{0}%'";
for (int i = 0; i < colCount; i++)
{
string colName = MyDataTable.Columns[i].ColumnName;
query.Append(string.Concat("Convert(", colName, ", 'System.String')", likeStatement));
if (i != colCount - 1)
query.Append(" OR ");
}
filterString = query.ToString();
Now you can get the rows where one of the columns matches your searchstring:
string currFilter = string.Format(filterString, searchText);
DataRow[] tmpRows = MyDataTable.Select(currFilter, somethingToOrderBy);
You can create a routine of search with an array of strings with the names of the columns, as well:
string[] elems = {"GUID", "CODE", "NAME", "DESCRIPTION"};//Names of the columns
foreach(string column in elems)
{
string expression = string.Format("{0} like '%{1}%'",column,
txtSearch.Text.Trim());//Search Expression
DataRow[] row = data.Select(expression);
if(row.Length > 0) {
// Some code here
} else {
// Other code here
}
}
You can get names of columns by using ColmunName Method. Then, you can search every column in DataTable by using them. For example, follwing code will work.
string str = "whatever";
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
if (row[column.ColumnName.ToString()].ToString().Contains(str))
{
return true;
}
}
}
You can create a filter expression on the datatable as well. See this MSDN article. Use like in your filter expression.
string filterExp = "Status = 'Active'";
string sortExp = "City";
DataRow[] drarray;
drarray = dataSet1.Customers.Select(filterExp, sortExp, DataViewRowState.CurrentRows);
for (int i=0; i < drarray.Length; i++)
{
listBox1.Items.Add(drarray[i]["City"].ToString());
}

How do I get the last cell in a row of a DataTable?

foreach(DataRow row in dt.Rows)
{
foreach(var cell in row.ItemArray)
{
builder.Append(cell.ToString());
if(cell != row.lastcell)
builder.Append("\t");
}
builder.Append(Environment.NewLine);
}
i need to make sure that cell!=the last cell in the row
how do i do this?
You don't need to do that. Just use string.Join instead:
string[] strings = Array.ConvertAll(row.ItemArray, x => x.ToString());
builder.Append(string.Join("\t", strings);
This would get you the last row:
row = (DataRow)table.Rows[table.Rows.Count-1];
You could completely avoid the last cell if you use a for loop:
for (int i=0; i<row.ItemArray-2;i++)
{
// do your code here, we are taking off the last cell with the -2
}
Use row.ItemArray[row.ItemArray.Length-1] to get a value of last cell
foreach(DataRow row in dt.Rows)
{
string separator = String.Empty;
foreach(var cell in row.ItemArray)
{
builder.Append(separator);
builder.Append(cell.ToString());
separator = "\t";
}
builder.Append(Environment.NewLine);
}

Categories