2017-07-29 21 views
0

我有嘗試使用含有通配符的字符串匹配的數據表的列名的問題。不匹配的數據表列c#通配符值

我有不同的列名的數據表,其中包括一個名爲像集如下:「PSA」,「公安局」,「PSC」,等。我想遍歷標題中包含Ps的所有列,並使用這些標題來提取數據。

目前,我有以下代碼未能找到任何匹配。我在if語句(「PsA」)中替換了一個直接值作爲測試,它工作正常;但是,當我使用通配符時,我找不到匹配項。我也試過Regex沒有運氣。

private void dfaSection_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     string psText = null; 
     string colID = "Ps*"; 

     offBox.Text = "";      //Clear textbox if a reselection occurs 
     psBox.Text = "";      //Clear textbox if a reselection occurs 

     info.offTitle = dfaSection.Text;  //Set textbox from variable 

     dt = opr.findOffByTitle(info);   //Get datatable from SQL database 

     if(dt.Rows.Count > 0) 
     { 
      offBox.Text = dt.Rows[0][5].ToString(); //Set textbox from datatable 

      foreach(DataColumn dc in dt.Columns)   //Loop through datatable columns 
      { 
       if (dc.ColumnName.ToString() == colID) //Check that column title matches test string  - Later addition--> && dt.Rows[0][dc].ToString() != null) 
       { 
        psText = dt.Rows[0][dc].ToString() + "\n\n"; //Add data from matched column to string variable 
       } 
      } 

      psBox.Text = psText;   //Set textbox from variable 
     } 

    } 

編輯:問題使用.Contains(colID)列名正在匹配,串固定,現在沒有被加載到psText變量,但我會花一些時間與得到它的工作。謝謝斯卡羅斯伊利亞斯。

+0

'我自己也嘗試用正則表達式不luck.'請告訴我們的代碼。 – mjwills

回答

0

我不這麼使用C failiar,但==肯定是不正確的方法。您需要使用 方法。正如我所說,我不熟悉它,但docs有一個很好的例子。

String s = "This is a string."; 
String sub1 = "this"; 
Console.WriteLine("Does '{0}' contain '{1}'?", s, sub1); 
StringComparison comp = StringComparison.Ordinal; 
Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp)); 
0

按照這個答案之前:Regular expression wildcard

這裏是代碼示例:

private static bool Match(string pattern, string stringToCheck) { 
    var finalPattern = pattern.Replace("*", ".*?"); 
    Regex regex = new Regex(finalPattern); 
    return regex.IsMatch(stringToCheck); 
} 
0

採取斷點檢查什麼是列名,colID在失敗moment.How你去解決問題,什麼時候甚至不知道價值? 使用dc.ColumnName.ToString().StartsWith()Contains()是好的,直到字符串endswith。

+0

我在運行時檢查了這些值。我也確認了原始價值的作用,消除了需要修整或類似價值的問題。我還測試了列名稱值,以確保它們正確迭代。 – Jexodus

+0

好的,那麼失敗時的colID值是多少?順便一提。從'colID'中刪除通配符並執行'.startswith' – user7234965

+0

colID是靜態的,並設置爲「Ps *」。我已經嘗試了刪除通配符並使用'StartsWith()'的建議,但是這也沒有奏效。 – Jexodus