問題:
需要對DataGridViewRow的下拉框列Item2所選內容進行判斷,看是否跟數據庫里面某個配置表的數據列Item1匹配。
如果用兩個foreach循環進行匹配,會導致邏輯復雜而且容易只break里面那層循環而忽略break外層循環而造成bug.
解決方案:
巧妙使用List,把配置表滿足條件的Item1統一裝到List,再使用List的Contains方法來判斷DataGridViewRow是否有行的Item2列是等於Item1相關項。
代碼:
List<string> list = new List<string>(); DataTable dt = xxxx; foreach (DataRow dr in dt.Rows) { list.Add(dr["Item1"].ToString()); } foreach (DataGridViewRow row in dgv.Rows) { if (list.Contains(row.Cells["Item2"].EditedFormattedValue.ToString())) { strXX = row.Cells["XXXX"].EditedFormattedValue.ToString(); break; } }