2015-06-10 80 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

相關問題