2013-10-01 68 views
1

我有一個數據的gridview,我想添加一個可以選擇多行的複選框列。通過點擊它,我想保存行的主鍵並更改行的css類。在asp.net回發中丟失的變量

使用this article(step 2)我創建了itemtemplate,添加了一個複選框(指定ID爲TransactionSelector),併爲其添加checkedChange()。在那裏我只改變一個css類的行並添加一個行索引到arraylist。但是,當我點擊按鈕與顯示此列表的事件,它沒有任何項目。

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" > 
     <Columns> 
      <asp:TemplateField> 
       <ItemTemplate> 
        <asp:CheckBox ID="TransactionSelector" runat="server" 
         oncheckedchanged="TransactionSelector_CheckedChanged" AutoPostBack="True" /> 
       </ItemTemplate> 
      </asp:TemplateField> 
      <asp:BoundField DataField="iTransactionsId" HeaderText="iTransactionsId" 
       SortExpression="iTransactionsId" /> 
      <asp:BoundField DataField="mAmount" HeaderText="mAmount" 
       SortExpression="mAmount" /> 
      <asp:BoundField DataField="vchTransactionType" HeaderText="vchTransactionType" 
       SortExpression="vchTransactionType" /> 
      <asp:BoundField DataField="dtDate" HeaderText="dtDate" 
       SortExpression="dtDate" /> 
      <asp:BoundField DataField="cStatus" HeaderText="cStatus" 
       SortExpression="cStatus" /> 
      <asp:BoundField DataField="test123" HeaderText="test123" 
       SortExpression="test123" /> 
     </Columns> 
     <RowStyle CssClass="unselectedRow" /> 
    </asp:GridView> 

</asp:Panel> 

<asp:Panel ID="InfoPanel" runat="server" CssClass="infoPanel"> 

    <asp:Button ID="ShowSelected" runat="server" Text="Button" 
     onclick="ShowSelected_Click" /> 

    <asp:Label ID="InfoLabel" runat="server"></asp:Label> 

</asp:Panel> 

升C代碼:

public partial class WebForm1 : System.Web.UI.Page 
{ 
    ArrayList indices = new ArrayList(); 


protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     GridView1.DataSourceID = "SqlDataSource1"; 
     GridView1.DataBind(); 
    } 
} 



protected void TransactionSelector_CheckedChanged(object sender, EventArgs e) 
{ 
    CheckBox cb = (CheckBox)sender; 
    GridViewRow row = (GridViewRow)cb.NamingContainer; 
    // row.CssClass = (cb.Checked) ? "selectedRow" : "unselectedRow"; 
    if (cb.Checked) 
    { 
    row.CssClass = "selectedRow"; 
    indices.Add(row.RowIndex); 
    } 
    else 
    { 
    row.CssClass = "unselectedRow"; 
    indices.Remove(row.RowIndex); 
    } 
} 

protected void ShowSelected_Click(object sender, EventArgs e) 
{ 
    InfoLabel.Text = ""; 
    foreach (int i in indices) 
    { 
    InfoLabel.Text += i.ToString() + "<br>"; 
    } 
} 

} 
} 

回答

3

你必須使用ViewState堅持變量回發。另外它的更好,如果你使用List<T>通用的實現,而不是ArrayList

ViewState["Indices"] = indices; 

並回收回來

indices = ViewState["Indices"] as ArrayList; 
0

正如哈比卜說,你可以使用ViewState。您也可以使用ControlState,如here所示。如果您的代碼位於自定義控件或用戶控件中,則您可能還需要覆蓋OnInit以

protected override void OnInit(EventArgs e) 
{ 
    base.OnInit(e); 
    Page.RegisterRequiresControlState(this); 
} 

請隨時以反饋回覆。我新發布答案。