I am trying to find a fast way to find a string in a Column in a DataTable and add it to a comboBox, and this is the code i tried so far :
adapter = new SqlDataAdapter("Select Id_Editeur ID,Libelle_Editeur Editeur from Editeur", myClass.cnx);
adapter.Fill(myClass.ds, "Editeur");
foreach (String str in myClass.ds.Tables["Editeur"].Columns[1].ToString())
editeurBox.Properties.Items.Add(str);
and that's doesn't work it gives me this error :
foreach statement cannot operate on variables of type
'System.Data.DataColumn' because 'System.Data.DataColumn' does not
contain a public definition for 'GetEnumerator'
How can I do that ? (I don't want the for loop solution).
foreach (var row in myClass.ds.Tables["Editeur"].AsEnumerable())
{
editeurBox.Properties.Items.Add(row[1].ToString());
}
or Full linq-style:
editeurBox.Properties.Items.AddRange(
myClass.ds.Tables["Editeur"]
.AsEnumerable()
.Select(dr => dr[1].ToString()
);
You can try with this code - based on LINQ Field operator
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<string>("RowNo") == "yourSearch"
select myRow;
I think you need to loop through the rows and grab the column that you want. Your code is trying to loop through the column collection which doesn't contain any data:
foreach (DataRow row in myClass.ds.Tables["Editeur"].Rows)
editeurBox.Properties.Items.Add(row[1].ToString());
string TableSelect;
DataTable dt = GetSomeData();
foreach (DataRow row in dt.Rows)
{
TableSelect = "EmplNo = " + row["EmplNo"].ToString();
DataRow[] foundrows;
foundrows = dt.Select(TableSelect);
if (foundrows.Count() > 0)
{
//do something useful here :)
}
}
Related
How can I iterate over an excel file?
I currently have a class using ExcelDataReader
Class => https://paste.lamlam.io/nomehogupi.cs#14fXzlopygZ27adDcXEDtQHT0tWTxoYR
I have a excel file with 5 columns
This is my current code, but it is not exporting the result that I expect ...
TextWriter stream = new StreamWriter("excel Path");
//foreach string in List<string>
foreach(var item in ComboList) {
var rows = ExcelHelper.CellValueCollection(item.Key);
foreach(var row in rows) {
stream.WriteLine(item.Key + "|" + row);
break;
}
}
stream.Close();
My result:
Column1|Row1
Column1|Row2
Column1|Row3
...
Column2|Row1
Column2|Row2
Column2|Row3
...
Expected:
Column1|Row1|Column2|Row1...
Column1|Row2|Column2|Row2...
Column1|Row3|Column2|Row3...
Thanks
This is the answer, I just needed to get the dataSet and iterate over it, very easy
var data = ExcelHelper.DataSet();
foreach (DataRow dr in data.Tables[0].Rows)
{
Console.WriteLine(dr["Column1"] + "|" + dr["Column2"]);
}
If I understand what you want truly! I think you need to add a method like RowValueCollection to your ExcelHelper as below:
public static IEnumerable<string[]> RowValueCollection()
{
var result = Data.Tables[0].Rows.OfType<DataRow>()
.Select(dr => dr.ItemArray.Select(ia => ia.ToString()).ToArray());
return result;
}
And then use it like this:
var rowValues = ExcelHelper.RowValueCollection();
foreach (var row in rowValues)
{
stream.WriteLine(string.Join("|", row));
}
HTH ;)
The first problem is that you are asking to write two items and only two items on a single line.
Would it help if you made the stream.writeline() statement into a .write() statement and then, after the inner loop performed a .writeline() which would terminate the line?
Apologies for not commenting but not enough Respect points to do so.
- Malc
I have the code for looping.
and I need the latest data from the results of the looping.
and from the last iteration, I just want to take the value "KodePosition" only. so how to get it?
The following code example looping.
please help me for this solution.
thank you
foreach (string data in splitRow)
{
string[] splitData = data.Split(';');
DataRow dr = dt.NewRow();
dr["KodePosition"] = splitData[0];
dr["NamaPosition"] = splitData[1];
dr["UserLogin"] = splitData[2];
dt.Rows.Add(dr);
}
If you are just trying to retrieve the value from the last row:
string lastKodePositionValue = dt.Rows[dt.Rows.Count-1]["KodePosition"];
If this is not what you are looking to do, please be more specific.
ASSUMING HERE THAT THE SPLITROW IS OF LIST TYPE.
If you want last row and then the position column then you can use this approach.
var lastRow = splitRow.Last();
var lastPosition = lastRow.Split(';').First();
Make sure you have using System.Linq.
Declare the outside the scope of the foreach a variable to store the "KodePosition" and set that for each update in the loop. Something like this
var lastKodePosition;
foreach (string data in splitRow)
{
string[] splitData = data.Split(';');
DataRow dr = dt.NewRow();
dr["KodePosition"] = splitData[0];
lastKodePosition = dr["KodePosition"];
dr["NamaPosition"] = splitData[1];
dr["UserLogin"] = splitData[2];
dt.Rows.Add(dr);
}
I want to query a specific value from a DataTable.
Lets say i have a DataTable which contains 2 columns:
id
item_name
Now what I want to do is like i would do it with mysql: SELECT * FROM "DataTable" WHERE item_name = 'MyItemName'
And then get the id that belongs to that 'item_name'...
int blah;
while (MyReader.Read())
{
blah = MyReader.GetInt32("id");
}
Now: how can I do this using DataTable?
I've got a snippet but I can't seem to show the returned value in a messagebox:
string test = Item1txt.Text;
var query = producten.Rows.Cast<DataRow>().Where(x => x.Field<string>("item_name") == test);
foreach (var st in query)
{
MessageBox.Show(st.ToString());
// how can i show the id that belongs to "test" ?
}
query will be an IQueryable<DataRow>, so st will be a DataRow. Try this:
foreach (var st in query)
{
MessageBox.Show(st.Field<int>("id").ToString());
}
Or if you know there will only item with that item_name, here's an alternative version which does essentially the same thing, but is probably a bit easier to understand:
var st = producten.Rows.Cast<DataRow>().FirstOrDefault(x => x.Field<string>("item_name") == test);
if(item != null)
{
MessageBox.Show(st.Field<int>("id").ToString());
}
You can use linq directly on the datatable without the need of Rows or the Cast.
var query = producten.AsEnumerable().Where(x => x.Field<string>("item_name") == test);
foreach (var st in query)
{
MessageBox.Show(st.Field<int>("id"));
}
I usually use the Rowfilter property of the defaultview of the datatable, but I must admit I never did LINQ myself, so there's probably a better way now...
Basically I have a DataTable with a rows containing part numbers and a couple of columns that contain information on those parts.
In order to compare those infos with the data we have in the database, I have determined I have one of two options.
Option 1 - Loop through each row and SELECT the data
void CompareData(DataTable dt) {
foreach (DataRow entry in dt.Rows) {
//select that row
DataRow dbEntry = ExecuteQuery("SELECT * FROM Parts WHERE partno='" + entry["partno"] + "'").Rows[0];
if (dbEntry["info1"] == entry["info1"]) {
//do something
} else {
//do something
}
}
}
Option 2 - SELECT all data at once and compare via loops
void CompareData(DataTable dt, string[] parts) {
DataTable dbEntries = ExecuteQuery("SELECT * FROM Parts WHERE partno IN('" + String.Join(parts, "','") + "')");
foreach (DataRow entry in dt.Rows) {
foreach (DataRow dbEntry in dt.Rows) {
if (dbEntry["partno"] == entry["partno"]) {
if (dbEntry["info1"] == entry["info1"]) {
//do something
} else {
//do something
}
}
}
}
}
They both seem pretty inefficient, so I'm not really sure what to do. Would LINQ speed this process up? I've never really used it but just browsing around it looks like something that could help.
Make as few DB calls as possible. You'll be more efficient 99.9% of the time. (general rule to code by)
I cannot use AsEnumerable() on DataTable, I'm using C# 3 but I'm just targeting 2.0 framework (LINQ capability is courtesy of LINQBridge). Is there any way I can make DataTable enumerable without using Select() ?
bool isExisting = (bdsAttachments.DataSource as DataTable).Select().Any(xxx => (string)dr["filename"] == filename);
Update:
I wanted it to make it look like this:
bool isExisting = (bdsAttachments.DataSource as DataTable).AsEnumerable().Any(xxx => (string)dr["filename"] == filename);
I'm getting an inkling that the Select method of DataTable returns a copy, I'm thinking to just use AsEnumerable, the problem is I'm just targeting 2.0 framework, System.Data.DataSetExtensions is not available
BTW, i tried this: http://cs.rthand.com/blogs/blog_with_righthand/archive/2006/01/15/284.aspx, but has compilation errors.
public static IEnumerable<DataRow> EnumerateRows(this DataTable table)
{
foreach (var row in table.Rows)
{
yield return row;
}
}
Allows you to call:
bool isExisting = (bdsAttachments.DataSource as DataTable).EnumerateRows().Any(dr => (string)dr["filename"] == filename);
IEnumerable<DataRow> rows = dataTable.AsEnumerable(); (System.Data.DataSetExtensions.dll)
IEnumerable<DataRow> rows = dataTable.Rows.OfType<DataRow>(); (System.Core.dll)
Keeping your enumerator strictly 2.0:
public static IEnumerable<DataRow> getRows(DataTable table)
{
foreach (DataRow row in table.Rows)
{
yield return row;
}
}
Then call with linqbridge like this:
bool isExisting = getRows(bdsAttachments.DataSource as DataTable).Any(row => (string)row["filename"] == filename);
You can try casting the DataTable as IEnumerable and iterate over the set:
//your data exists as a DataTable
DataTable dt = (DataTable)bdsAttachments.DataSource;
foreach (DataRow row in dt)
{
if (row["filename"] == filename)
return row;
}
The foreach will iterate through the list and search of the filename (I assume you're searching for the first DataRow with that filename, not all rows that match the filename).