C#多文本框过滤DataGridView时RowFilter报Mod运算符语法错误
Fixing "Missing operand before 'Mod' operator" in DataView RowFilter
Let's break down exactly why you're hitting this error and how to fix it cleanly:
The Root Cause
Your section number filter line has two critical issues:
sb.Append("section_number like %" + Int32.Parse(section.Text) + "%");
- Missing quotes around wildcards: In DataView's RowFilter syntax (which uses VB-style expressions),
%without single quotes gets interpreted as the Mod (modulo) operator instead of a wildcard. This is why you're seeing the "Missing operand before 'Mod' operator" error. - Incorrect LIKE usage on numeric fields:
section_numberis a numeric type, butLIKEis designed for string comparisons. Directly using it on a number will cause parsing issues.
Fixed Code
Here's a revised version that fixes these issues, adds error handling, and reduces injection risks:
StringBuilder sb = new StringBuilder(); // Handle document name search if (!string.IsNullOrEmpty(documentName.Text)) { // Escape single quotes to avoid syntax errors (e.g., names like O'Neil) string safeDocumentName = documentName.Text.Replace("'", "''"); sb.Append($"document_name LIKE '%{safeDocumentName}%'"); } // Handle section number search if (!string.IsNullOrEmpty(section.Text)) { // Add AND if we already have a filter if (sb.Length > 0) { sb.Append(" AND "); } // Validate input is a valid integer first if (int.TryParse(section.Text, out int sectionNumber)) { // Convert numeric field to string for LIKE comparison sb.Append($"CONVERT(section_number, System.String) LIKE '%{sectionNumber}%'"); } else { // Handle invalid input (adjust this to fit your UI flow) MessageBox.Show("Please enter a valid numeric section number."); return; } } // Apply the filter safely DataTable dataTable = data.DataSource as DataTable; if (dataTable != null) { dataTable.DefaultView.RowFilter = sb.Length > 0 ? sb.ToString() : string.Empty; }
Key Improvements
- Properly quoted wildcards: The
%wildcards are now wrapped in single quotes, so they're interpreted correctly by the RowFilter parser. - Numeric field handling: We use
CONVERTto turn the numericsection_numberinto a string before usingLIKE—this is required for partial matching on numeric fields in DataView. - Safer input handling:
string.IsNullOrEmptyis more readable and reliable than checkingLength > 0.int.TryParseprevents crashes if the user enters non-numeric text in the section field.- Escaping single quotes in the document name avoids syntax errors from names containing apostrophes.
- Cleaner conditional logic: The filter building is more structured and easier to maintain.
Bonus Tip
If you only need exact matches for the section number (not partial matches), replace the LIKE line with a direct numeric comparison—it's faster and simpler:
sb.Append($"section_number = {sectionNumber}");
内容的提问来源于stack exchange,提问作者HowdyCowboy
相关产品推荐
相关产品推荐

