I have the following problem.
I have a DataTAble object that represent a single column table, the column is named VulnerabilityReferenceId, something like this:
VulnerabilityReferenceId
167554
167555
167556
167557
167558
167559
167560
167561
So I want create a foreach that access to these row and put the value into a variable
I have done:
foreach (DataRow row in _dt.Rows)
{
Debug.WriteLine("VulnerabilityReferenceId: " );
}
But what can I do to access to the value of the current row and put it into an int variable?
This could be an approach that read the field and convert it to the required datatype.
It requires the reference to DataSetExtension assembly from NET3.5 where you could start to find the DataRowExtensions class
foreach (DataRow row in _dt.Rows)
{
int id = row.Field<int>("VulnerabilityReferenceId");
.....
}
Note: I assume that the field VulnerabilityReferenceId is of type integer
You can use column name as an indexer to get the value as object
foreach (DataRow row in _dt.Rows)
{
int vulRefId=Convert.ToInt32(row["VulnerabilityReferenceId"]);
Debug.WriteLine("VulnerabilityReferenceId: " +vulRefId );
}
Try the below:
for(int i=0;i<_dt.Rows.Count;i++)
{
Debug.WriteLine("VulnerabilityReferenceId: "+dt.Rows[i][0].ToString());
}
foreach (DataRow row in _dt.Rows)
{
String stringVal = row["VulnerabilityReferenceId"].ToString();
int myId = Convert.ToInt32(stringVal);
}
Related
I have a DataTable with multiple rows. I'm using a foreach loop to loop through each item and return the name. This is returning the same (1st) value for each row. What have I done wrong?
DataTable table = new DataTable();
table.Columns.Add("tag", typeof(string));
string name = hfSelected.Value;
string[] names = name.Split(',');
for (int i = 0; i < names.Length; i++)
table.Rows.Add(new object[] { names[i] });
DataRow row = table.Rows[0];
foreach (var item in table.Rows)
{
Value = row["tag"].ToString() // this is returning the same value for both items in the table.
}
In a comment you mentioned that you get the error:
cannot apply indexing with [] to an expression of type object
when trying to access item["tag"] in the foreach loop.
You need to explicitly declare the DataRow in the foreach.
// declare DataRow here, not var
foreach (DataRow item in table.Rows)
{
// use item here
Value = item["tag"].ToString(); // use += to concatenate string
}
The reason is that the DataRowCollection implements a non-generic IEnumerable so you index an object instead of DataRow. The solution above casts to a DataRow.
I would recommend looking at the Field<T>() and AsEnumerable() methods from System.Data.DataSetExtensions. AsEnumerable() returns an IEnumerable<DataRow>. Field() provides strongly typed access to the values (ie it casts/converts the types for you).
Then you can do:
foreach (var item in table.AsEnumerable())
{
// item is a DataRow here
var myString = item.Field<string>("tag"); // gets string
// you can also do
var myInt = item.Field<int>("Id"); // gets int
var myDate = item.Field<DateTime?>("Date"); // gets nullable DateTime?
var myValue = item.Field<decimal>("Price"); // gets decimal
}
Carl is correct, this is producing the same output, because inside the iteration, you use the same row, all the time. You should use 'item', instead of 'row' there (you don't need 'row' at all).
The exception you receive is because you declared 'item' with a dynamic type, it's
foreach (var item in table.Rows)
You can try
foreach (DataRow item in table.Rows)
this way, you'll be able to get the column info.
your iteration seems to be using the same 'row' variable instead of the 'item' variable you defined in the foreach statement.
I want to be able to detect 2 similar strings in my datatable. How do I do that?
foreach (DataRow row2 in visualDataTable.Rows)
{
foreach (char server in serverName)
{
foreach(similar string in servername)
{
// do something..
}
}
}
The simplest approach would involve iterating two times through your rows and compare each value with one and another (similar to your above approach):
foreach (DataRow row in visualDataTable.Rows)
{
foreach (DataRow compareRow in visualDataTable.Rows))
{
if(row["<your column>"] == compareRow["<your column>"])
{
// The two rows have the same column value for <your column>
// Do something
}
}
}
I am Working in asp.net and c#.
I have a datatable in my application with one column.I want to iterate through that column values and check those values with someother value.please tell me how to do that.I tried it with foreach but its not working.
Code:
foreach (DataRow dr in dt.Rows)
{
int code = Convert.ToInt32(dt.Rows[0]["Code"]);
if (code == pcode)
{
//do something
}
else
{ }
}
Note:
dt is my datatable with column code.I want to compare all values in column code with pcode.
int code = Convert.ToInt32(dr["Code"]);
Although you might want to check for NULL also :)
Inside your loop, access dr, instead of dt.Rows[0].
You are always accessing the first row:
dt.Rows[0]["Code"] // use dr instead of dt.Rows[0]
dt is my datatable with column code.I want to compare all values in
column code with pcode.
So am i right when i assume that you want to compare all values with one variable, if all fields equal this value, a bool variable should be true, otherwise false?
You can use Linq:
var allEqual = dt.AsEnumerable()
.All(r => r.Field<int>("Code") == pcode);
Enumerable.All determines whether all elements of a sequence satisfy a condition.
foreach (DataRow dr in dt.Rows)
{
object o = dr["Code"];
if (o != DBNull.Value) // Check for null
{
int code = Convert.ToInt32(o);
if (code == pcode)
{
//do something
}
else
{ }
}
}
I need to iterate the columnname and column datatype from a specific row. All of the examples I have seen have iterated an entire datatable. I want to pass a single row to a function to do a bunch of conditional processing. I want to separate the conditional processing for ease of readability.
This is what I have:
private void doMore(DataRow dr)
{
foreach (DataColumn c in dr.ItemArray) //loop through the columns.
{
MessageBox.Show(c.ColumnName.ToString());
}
}
The error returned is
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Data.DataColumn'.
How would I get the column name from the row or do I have no choice and must pass the entire datatable to the function?
You would still need to go through the DataTable class. But you can do so using your DataRow instance by using the Table property.
foreach (DataColumn c in dr.Table.Columns) //loop through the columns.
{
MessageBox.Show(c.ColumnName);
}
You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:
static class Extensions
{
public static string GetColumn(this DataRow Row, int Ordinal)
{
return Row.Table.Columns[Ordinal].ColumnName;
}
}
Then call it using:
string MyColumnName = MyRow.GetColumn(5);
You need something like this:
foreach(DataColumn c in dr.Table.Columns)
{
MessageBox.Show(c.ColumnName);
}
use DataTable object instead:
private void doMore(DataTable dt)
{
foreach(DataColumn dc in dt.Columns)
{
MessageBox.Show(dc.ColumnName);
}
}
I have populated a DataTable from a stored procedure in an older web application written in
C# under .NET 2.0 / Visual Studio 2005.
I'm trying to populate a List with the values in the DataTable, but I keep running up against a couple issues.
My conversion process looks like this:
List<int> SpecialVendorList = new List<int>();
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
{
SpecialVendorList.Add(column["ChildVendorId"]);
SpecialVendorList.Add(column["ParentVendorId"]);
}
}
which gives me the following error:
Can not apply indexing with [] to an expression of type 'System.Data.DataColumn'
for each of the SpecialVendorList.Add() methods.
Seems like you're trying to get column values for each row. You only the first foreach loop:
List<int> SpecialVendorList = new List<int>();
try
{
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
SpecialVendorList.Add(Convert.ToInt32(datarow["ChildVendorId"]));
SpecialVendorList.Add(Convert.ToInt32(datarow["ParentVendorId"]));
}
}
catch(FormatException fe)
{
//handle the error
}
The string index here will get that column's value in that specific row
you need to add the actual values from the rows using the column as the index:
List<int> SpecialVendorList = new List<int>();
foreach (DataRow datarow in GetAllSpecialVendors().Rows)
{
//Loop through each row
foreach (DataColumn column in GetAllSpecialVendors().Columns)
{
int val;
if (int.TryParse(datarow[column].ToString(), out val))
SpecialVendorList.Add(val);
}
}