C# DataGridView.Rows.ToString() - c#

I am trying to store the values of each of my rows in a string.
If I try to do DataGridView.Rows.ToString() I get
System.Windows.Forms.DataGridViewRowCollection
Not even close to what I need.
Any ideas?

I think you're looking for something on a per row basis. If so, I suggest the following.
private static IEnumerable<string> GetRowValues(this DataGridView dgv)
{
var list = new List<string>(dgv.Rows.Count);
foreach (DataGridViewRow row in dgv.Rows)
{
var sb = new StringBuilder();
foreach (DataGridViewCell cell in row.Cells)
{
sb.Append(cell.ToString());
}
list.Add(sb.ToString());
}
return list.AsReadOnly();
}

You need to do something like this:
StringBuilder sb = new StringBuilder();
for(int row=0; row<DataGridView.Rows.Count; row++)
{
for(int col=0; col < DataGridView.Columns.Count; col++)
{
sb.Append(DataGridView.Row[row][col].ToString());
}
}
sb.ToString(); // that will give you the string you desire
EDIT I didn't run this through to check that it runs but it should at least give you a starting point. Also, this will give you all rows. If you want just one row, change the variable row to the row number you need (keep in mind that it is zero-based).

Use the for each statement to iterate through each row in the Datagridview.
foreach (DataGridViewRow datarow in dataGridView.Rows)
{
string col1 = datarow.Cells["Col1"].Value.ToString();
string col2 = datarow.Cells["Col2"].Value.ToString();
string col3 = datarow.Cells["Col3"].Value.ToString();
}

Foreach(Var row in DataGridView.Rows)
{
Foreach(Var cell in row.Cells)
{
Var str = cell; // this is the string you want
}
}
Something like the code above. Excuse the formatting typed on iPad.

Related

C# datagridview find and get value

I have some text and a datagridview with 5 columns. How can I find this text in the first column and get values from other columns in the same row?
I think the code lines will give you the datagridview row index for the value:
String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
{
if(row.Cells[1].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
then you can do:
dataGridView1.Rows[rowIndex].Selected = true;
It would be :
List<string> Values = new List<string>();
foreach (DataRow row in YourDataTable.Rows)
{
if (row["firstColumn"].ToString() == yourText)
{
Values.Add(row["firstColumn"].ToString());
Values.Add(row["secondColumn"].ToString());
Values.Add(row["thirdColumn"].ToString());
Values.Add(row["fourthColumn"].ToString());
Values.Add(row["fifthColumn"].ToString());
}
}

Get a string value from a data table row using the data table's first row as identifier

I have searched several threads and cannot seem to find a C# solution. I have a string list and a datatable in C#. I need to be able to iterate through my data table's rows, then iterate through my list to obtain a header value (row[0]) and use that to assign to a variable.
Here is what I have so far:
private void setInformation(DataTable dt, List<string> text)
{
foreach(DataRow row in dt.Rows)
{
if (dt.Rows.IndexOf(row) != 0)
{
for (int i = 0; i <= text.Count; i++)
{
string s;
string ValueNeeded;
s = text[i];
ValueNeeded = dt.Columns.IndexOf(text).ToString();
//needs to be the current dt rows value for the header /
//row(0) with that string identifier
//in VB its something like
//DT.Rows(0).Item(text).ToString
}
}
}
}
All I have is the first row's string value; as I iterate through the DT, I'll need to get that "cell's value by leveraging the first rows value. I need the current cell each time.
You can get the value of any cell by referencing the row[index] and the column name string
string xyz= dt.Rows[0]["columnName"].ToString();
OK so assuming the List<string> text parameter contains values of the first row (not the column names) in your DataTable, and you're looking to get the corresponding cell in each row, something like this should work (haven't tested it)
private void setInformation(DataTable dt, List<string> text)
{
var cache = new Dictionary<string, int>(); //cache column numbers
foreach(var entry in text) cache[entry] = getColumnNumberByValue(dt, entry);
for(int i=1; i < dt.Rows.Count; i++)
{
foreach(var entry in text)
{
var columnIndex = cache[entry];
if(columnIndex != -1)
{
var valueNeeded = dt.Rows[i][columnIndex].ToString();
}
}
}
}
private int getColumnNumberByValue(DataTable dataTable, string text)
{
for(int i=0; i < dataTable.Columns.Count; i++)
{
if(dataTable.Rows[0][i].ToString() == text) return i;
}
return -1;
}

Reading data from dataGridView instead of a csv file in C#

I have written a C# code to read data from a csv file. The data is in the form say:
2,3,4,5,6
4,2,4,5,6
4,5,6,3,2
5,3,5,6,3
The code to read it is:
var lines = File.ReadLines("Data.csv");
var numbers = ProcessRawNumbers(lines);
The function ProcessRawNumbers is as follows:
private static List<List<double>> ProcessRawNumbers(IEnumerable<string> lines)
{
var numbers = new List<List<double>>();
/*System.Threading.Tasks.*/
Parallel.ForEach(lines, line =>
{
lock (numbers)
{
numbers.Add(ProcessLine(line));
}
});
return numbers;
}
private static List<double> ProcessLine(string line)
{
var list = new List<double>();
foreach (var s in line.Split(Separators, StringSplitOptions.RemoveEmptyEntries))
{
double i;
if (Double.TryParse(s, out i))
{
list.Add(i);
}
}
return list;
}
I would like to do the same with DataGridView. How can this be achieved?
In DataGridView I give input as follows:
Also, is it possible to have the number of columns change dynamically?
Data entered in a DataGridView is stored in its rows and cells. To exctract the data, you have to manually iterate over the rows and cell:
public List<string[]> ExtractGridData(DataGridView grid)
{
int numCols = grid.Columns.Count;
List<string[]> list = new List<string[]>();
foreach (DataGridViewRow row in grid.Rows)
{
if (row.IsNewRow) // skip the new row
continue;
string[] cellsData = new string[numCols];
foreach (DataGridViewCell cell in row.Cells)
if (cell.Value != null)
cellsData[cell.ColumnIndex] = cell.Value.ToString();
list.Add(cellsData);
}
return list;
}
If you want to change the columns dynamically, you can access the Columns property of the grid. For example, to add a column you can write:
dataGridView1.Columns.Add("NewColumn", "New Column");
Also note that using Parallel.ForEach in your scenario has no advantage, because you have to process the data sequentially, and by using lock statement, you forced the sequential processing. So there is no parallel proccessing.

Replace value in DataColumn

How to replace column value when looping rows?
My DataTable has two columns, I want to replace the value of the first column on every row.
I'm unable to get or set column value. So far I only manege to access DefaultValue and ColumnName etc.
Even if creating new DataColumn(), I'm not able to set its value.
Feels like I'm missing some fundamental stuff here...
foreach (var row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
// column Unable to get or set value
}
}
Running .NET Framework 3.5, should I use linq?
for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
{
dataTable.Rows[rowIndex][0] = "Replacing value";
}
Since DataTable.Rows implements only IEnumerable and not IEnumerable<T> you need to cast it to DataRow in the foreach and you cannot use var:
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
row.SetField(column, newValue);
}
}
You could do this
foreach (DataRow row in table.Rows)
{
row.SetField(table.Columns.Cast<DataColumn>().Single(column => column.Ordinal == 0), "new");
}

How can I know a row index while iterating with foreach?

in the next example how can I know the current row index?
foreach (DataRow temprow in temptable.Rows)
{
//this.text = temprow.INDEX????
}
You have to create one yourself
var i = 0;
foreach (DataRow temprow in temptable.Rows)
{
this.text = i;
// etc
i++;
}
or you can just do a for loop instead.
I have a type in MiscUtil which can help with this - SmartEnumerable. It's a dumb name, but it works :) See the usage page for details, and if you're using C# 3 you can make it even simpler:
foreach (var item in temptable.Rows.AsSmartEnumerable())
{
int index = item.Index;
DataRow value = item.Value;
bool isFirst = item.IsFirst;
bool isLast = item.IsLast;
}
If you can use Linq, you can do it this way:
foreach (var pair in temptable.Rows.Cast<DataRow>()
.Select((r, i) => new {Row = r, Index = i}))
{
int index = pair.Index;
DataRow row = pair.Row;
}
You actually Don't. One of the beauties with foreach is that you don't have the extra set of code handling incrementing and checks on the length.
If you want to have your own Index you would have to do something like this
int rowindex = 0;
foreach (DataRow temprow in temptable.Rows)
{
//this.text = temprow.INDEX????
this.text = rowindex++;
}
int rowIndex = temptable.Rows.IndexOf(temprow);
It's not possible with a standard foreach loop. The simplest way is to use a for loop
for ( int i = 0; i < temptable.Rows.Count; i++ ) {
DataRow temprow = (DataRow)temptable.Rows[i];
...
}
Another option is to use an extension method
public static void ForEachIndex<T>(this IEnumerable<T> e, Action<T,int> del) {
var i = 0;
foreach ( var cur in e ) {
del(cur,i);
}
}
...
temptable.Rows.Cast<DataRow>.ForEachIndex((cur,index)
{
...
});
Hey there's a much faster way I think. No iteration required!
First, declare a static variable for the Friend RowID Field of the DataRow:
Private Shared RowIDFieldInfo As System.Reflection.FieldInfo = GetType(DataRow).GetField("_rowID", System.Reflection.BindingFlags.NonPublic Or System.Reflection.BindingFlags.Instance)
Then All you need to do to use it is:
RowIDFieldInfo.GetValue(MyDataRow) - 1
I have not tested this after resorting or filtering.
In my case I haven't a need to do that, so this works.
Better late than never...
foreach (DataRow temprow in temptable.Rows)
{
temptable.Rows.IndexOf(temprow);
}
Write any Cell number and get RowIndex
foreach (var item in datagridview.Rows)
{
//TextBox1.Text= item.Cells[0].RowIndex.ToString();
}
Either use a for-loop, or use an integer follow along:
int count =0;
foreach (DataRow temprow in temptable.Rows)
{
//count is the index of the row in the array temptable.Rows
//this.text = temprow.INDEX????
++count;
}
You can use the standard for loop to get the index
for(int i=0; i<temptable.Rows.Count; i++)
{
var index = i;
var row = temptable.Rows[i];
}
While LFSR's answer is right, I'm pretty sure calling .IndexOf on just about any collection/list is going to enumerate the list until it finds a the matching row. For large DataTable's this could be slow.
It might be better to for (i = 0; i < temptable.Rows.Count; i++) { ... } over the table. That way you have the index without imposing a find-the-index tax.
The alternative way to retrieve data by using index instead of using column name
foreach (DataRow temprow in temptable.Rows)
{
String col1 = temprow[0].ToString().Trim();
String col2 = temprow[1].ToString().Trim();
}
Hope it help

Categories

Resources