2015-06-10 83 views
0

我基本上试图从excel文件读取并在该文件中找到某个ID号。现在它打印所有的行作为匹配,我想帮助找出原因。在输入字符串行中匹配单元格

// 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"); 
    } 
} 
+1

foreach循环会遍历所有行的,就像一个普通的循环从0到Rows.Count。我不明白为什么你不能像你目前正在做的那样简单地使用foreach语句。 – HaukurHaf

+2

我不认为从foreach转换为for会解决任何问题。相反,我会检查你的匹配功能,我敢打赌错误在那里。你的错误似乎是你比较textBox3这两个匹配,然后打印每一行相同的东西。您需要检查行是否与您正在搜索的内容匹配。 – bkribbs

+0

你的Excel工作表是什么样子的,是同一列中的所有ID,并且该列中的索引或名称总是相同?如果是这样,您可以直接将该列与您的输入值进行比较,然后在找到该行后编写整行 – Domitius

回答

0

我仍然会使用foreach循环,然后添加一个简单的计数器,并通过counter++每次增加它你循环,当你找到它,你可以在增值&的数据集合,所以你以后可以参考它。

foreach比for循环要安全得多,有时候for循环更受欢迎,但我不认为这是其中的一个。

0

你的错误不是for vs foreach循环,而是你正在做的匹配。试试这个。

您也没有正确读取行,您应该只查看所需的一列。将下面的列变量更改为正确的列。

这和你的代码之间的主要区别是你想检查迭代中的每一行,然后如果它是匹配,打印一行这样说。这与你最初做的比较,你比较一个字符串一次,如果匹配,每行打印一遍又一遍。

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"); 
    } 
} 
+0

如果您仍然需要,我已经更新了一下 – bkribbs

0

您可以通过下面的代码 如果你想匹配值一些Excel列E.G.解决问题ID在for循环 认沽条件....因为我觉得你想与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); 
    } 
} 
+0

第一次匹配,验证来自Textbox3的输入 Second myMatch Validate从Excel输入文本框中的每个值... – TeamKhurram

+0

是的!非常感谢! – Cscience18

相关问题