2012-05-28 32 views
3

我有一個相當簡單的GridView。這是列標記:Gridview點擊標題排序觸發行命令

<Columns> 
       <asp:TemplateField HeaderText="JD Name" SortExpression="FullName" 
        HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="180px" > 
        <ItemTemplate> 
         <asp:LinkButton CommandName="edt" CommandArgument='<%#Eval("JurisdictionID") %>' runat="server" Text='<%#Eval("FullName") %>' /> 
        </ItemTemplate> 
       </asp:TemplateField> 

       <asp:BoundField HeaderText="JD Abbreviation" ItemStyle-Width="200px" DataField="JDAbbreviation" SortExpression="JDAbbreviation" 
        HeaderStyle-HorizontalAlign="Center" /> 

       <asp:TemplateField 
        HeaderStyle-HorizontalAlign="Center" > 
        <ItemTemplate> 
         <asp:LinkButton ID="lnkStat" CommandName="inac" CommandArgument='<%#Eval("JurisdictionID") %>' 
         runat="server" Text='<%#Utils.GetStatusString((bool) Eval("IsActive")) %>' /> 
        </ItemTemplate> 
       </asp:TemplateField> 

      </Columns> 

然而,當我點擊排序列,它首先觸發行命令事件,然後來排序事件。任何人都可以告訴我我在做什麼錯誤?在RowCommand參數中,我得到了SortExpression。這對我來說真的很有趣!

回答

3

Sortrow command。查看MSDN GridView.RowCommand Event article瞭解更多詳情。

在您的行命令事件中,您應該添加if語句,以便您可以確定何時執行行命令代碼。使用e.CommandName。

void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e) 
{ 
    // If multiple buttons are used in a GridView control, use the 
    // CommandName property to determine which button was clicked. 
    if(e.CommandName=="Add") 
    { 
    // Convert the row index stored in the CommandArgument 
    // property to an Integer. 
    int index = Convert.ToInt32(e.CommandArgument); 

    // Retrieve the row that contains the button clicked 
    // by the user from the Rows collection. 
    GridViewRow row = ContactsGridView.Rows[index]; 

    // Create a new ListItem object for the contact in the row.  
    ListItem item = new ListItem(); 
    item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " + 
    Server.HtmlDecode(row.Cells[3].Text); 

    // If the contact is not already in the ListBox, add the ListItem 
    // object to the Items collection of the ListBox control. 
    if (!ContactsListBox.Items.Contains(item)) 
    { 
     ContactsListBox.Items.Add(item); 
    } 
    } 
} 
相關問題