Search code examples
asp.netvb.netsortinggridviewdatabound

Sorting databound textboxes in Gridview numerically


I currently have a gridview that is populated by a stored procedure. This stored procedure can not be altered. On my page, I have a drop down box. This dropdown contains all of the column names for the gridview. When a user clicks on a value, the gridview is sorted by that column.

All of that is no problem. However, the problem occurs when I try to sort one of the columns chronologically. I have this:

<asp:TemplateField HeaderText="RollNo" SortExpression="RollNo" >
        <ItemTemplate>
             <asp:TextBox ID="RollNoBox" runat="server" MaxLength="2" AutoCompleteType="None"  Width="35px"
               Text='<%# Bind("RollNo") %>'>
             </asp:TextBox>
        </ItemTemplate>
 </asp:TemplateField>

When I click on this column to sort, it behaves like this:

    Original:               Actual Sorted:  
    1                             null
    2                             null
    3                             null
    4                             null
    5                             1
    6                             2
    7                             3
    8                             4
    9                             5
    10                            6 
    11                            7 
    null                          8
    null                          9
    null                          10
    null                          11

However, I want the sort to be the SAME as the original (So I can add additional filters).

How can I do this?

Here is my sort function:

Protected Sub SortGrid()
    Dim sortexpression As String
    If DropDownList1.SelectedValue <> "Select" Then
        sortexpression = DropDownList1.SelectedValue
    End If

        M1SchedView.Sort(sortexpression, SortDirection.Ascending)

End Sub

This is a bit altered from my actual function as I have multiple sorts in my page.

EDIT: I was able to get the SP edited so that the column is now an integer. However, now it places the null values before the numbers. If this could be switched, I would be set.


Solution

  • RollNo seems to be a string

    add another property int RollNoNumeric and define it so

    public int RollNoNumeric
    {
        get { return string.IsNullOrEmpty(this.RollNo) 
                  ? int.MaxValue 
                  : Convert.ToInt32(RollNo); }
    }
    

    then change your SortExpression to

    SortExpression="RollNoNumeric"