Using 'SUBSTRING(expression, startIndex, length)' with BindingSource on DataColumn

非 Y 不嫁゛ 提交于 2019-12-13 20:48:09

问题


I am trying to filter a numeric string by matching the start of the source string and the length of the search string.

All the filtered columns are strings. Most are just words, but there is one column that has values that look like this 001302:Alt#. The underlying data source sucks, but I cannot change the structure. The numbers are grouped based on the left-hand values (i.e. 050110 and 050534 are both related to client(05), 052123 is related to client(05) invoices(2)). My users want to be able to search the data in the DataGridView and filter that column by group (i.e. Enter 05 and see everything that starts with 05, or 052 and see 052000-052999)

I am generating the filter string and setting the Filter property on the BindingSource using the DataSet as DataSource and the Table as DataMember. The rest of my filtering works, the only problem I am having is with the numeric filter. When I set the BindingSource.Filter property, it throws an ArgumentOutOfRange exception.

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Data.dll Additional information: Substring() argument is out of range.

I thought I might be firing this against an empty row, or one that only had a few digits, but it is firing with only one character. Therefore, the length argument should be valid, but it is still throwing the exception.

bool firstColumn = true;
foreach (DataColumn column in FilteredColumns.Keys)
{
    if (FilteredColumns[column])
    {
        if (!firstColumn) fieldFilter.Append(") OR ("); else firstColumn = false;

        int numericFilter;
        if (int.TryParse(filterWord, out numericFilter))
        {
            fieldFilter.Append(String.Format("SUBSTRING({0}, 0, {2}) = {1}", column.ColumnName, filterWord, filterWord.Length));
        }
        else
            {
            fieldFilter.Append(String.Format("{0} like '%{1}%'", column.ColumnName, filterWord));
            }
    }
}

I am sure I am just missing something stupid. I thank you in advance for pointing out my error(s)!


回答1:


I was making the assumption that the DataColumn Expression SUBSTRING behaved the same as String.Substring. However, the SUBSTRING Expression is a 1 based index, whereas the String.Substring method starts its index at 0.



来源:https://stackoverflow.com/questions/23049995/using-substringexpression-startindex-length-with-bindingsource-on-datacolu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!