Reputation: 25
I am basically trying to read from an excel file and find a certain ID Number in that file. Right now it is printing all of the rows as a match and I would like help figuring out why.
// input to search for
string value = textBox3.Text;
// verify the input is the correct format
Match match = Regex.Match(value, @".*[0-9].*");
Match myMatch = Regex.Match(value, textBox3.Text);
Console.WriteLine(value);
foreach (DataRow row in xlsDs.Rows)
{
if (match.Success && myMatch.Success)
{
Console.WriteLine(textBox3);
Console.Write(row.ItemArray.ToString());
Console.WriteLine("This was found");
}
}
Upvotes: 0
Views: 803
Reputation: 734
Your error isn't the for vs foreach loop, it's the matching you're doing. Try this instead.
You also were not reading the rows in correctly, you should only look at the one column that you need. Change the column variable below to the correct column.
The primary difference between this and your code is that you want to check each row in the iteration and then if it is a match, print a line saying so. This is compared to what you did originally, where you compare one string once and if that is a match, print that over and over for each row.
string columnName = "Employee ID"; // change to the correct header
// Check the ID from the textbox to make sure it is valid?
Match match = Regex.Match(textBox3.Text @".*[0-9].*");
for(int i = 0; i < xlsDs.Rows.Count; i++)
{
// get the current row
DataRow row = xlsDs.Rows[i];
// get the ID from the row
string idValue = row[columnName].ToString();
// check if the row value is equal to the textbox entry
bool myMatch = idValue.Equals(textBox3.Text);
// if both of the above are true, do this
if (match.Success && myMatch == true)
{
Console.Write(idValue);
Console.WriteLine(" -This id was found");
}
}
Upvotes: 0
Reputation: 107
You can solve it by following code if you want to match value to some excel column E.G. ID Put condition in for loop .... Because i think you want to match value with some column of excel..
string value = textBox3.Text;
Match match = Regex.Match(value, @".*[0-9].*");
Console.WriteLine(value);
int TotalRows = xlsDs.Rows.Count;
for(int i=0;i<TotalRows;i++)
{
DataRow row = xlsDs.Rows[i];
String row_Val=row["Cell_Name"].ToString();//Put Cell you want to match IE ID
Match myMatch = Regex.Match(row_Val, textBox3.Text);
if (match.Success && myMatch.Success)
{
Console.WriteLine(textBox3);
Console.Write(row.ItemArray.ToString());
//Console.WriteLine(row["Cell_Name"]);//if you want to print a specific cell
Console.WriteLine("This was found at row "+i);
}
}
Upvotes: 0
Reputation: 476
I would still use a foreach loop, then add a simple counter and increment it via counter++
every time you loop, when you find it you can add that value & the data to a collection so you can the reference it later on.
foreach is much safer than a for loop, there are times where for loop is much preferred but I don't see this being one of those times.
Upvotes: 0