2010-08-25 41 views
5

當中繼控件中單擊CheckBox時,我需要在中繼器的某一行上執行一些服務器端邏輯。Repeater或DataList中的複選框OnClick/ItemCommand

任何人都知道如何去做這件事?

我看到它的方式你不能消防項目命令,如果你使用CheckBoxes OnClick你不能得到中繼器行。

回答

9

以下是我過去如何完成類似工作的快速模擬。

<asp:Repeater id="repeater1" runat="server" OnItemDataBound="repeater1_OnItemDataBound" > 
     <ItemTemplate> 
      <asp:CheckBox ID="chk" runat="server" OnCheckedChanged="Check_Changed" AutoPostBack="true" /> 
     </ItemTemplate> 
    </asp:Repeater> 

代碼隱藏:

public class Model { 
     public int Id { get; set; } 
     public string Name { get; set; } 
    } 

    public partial class Checkboxes : System.Web.UI.Page { 
     protected void Page_Load(object sender, EventArgs e) { 
      if(!IsPostBack) { 
       repeater1.DataSource = new List<Model> { 
           new Model { Id = 1, Name = "a" }, 
           new Model { Id = 2, Name = "b" }, 
           new Model { Id = 3, Name = "c" } }; 
       repeater1.DataBind(); 
      } 
     } 

     protected void repeater1_OnItemDataBound(Object sender, RepeaterItemEventArgs e) { 
      if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { 
       var item = e.Item.DataItem as Model; 
       if (item != null) { 
        var chk = e.Item.FindControl("chk") as CheckBox; 
        if (chk != null) { 
         chk.Text = item.Name; 
         chk.InputAttributes.Add("value", item.Id.ToString()); 
        } 
       } 
      } 
     } 

     protected void Check_Changed(Object sender, EventArgs e) { 
      var id = ((CheckBox) sender).InputAttributes["value"]; 
      //you now have access to the item id and can manipulate at will. 
     } 
    } 
+0

感謝這應該工作。希望有一個更少的方式... +1 – Jason 2010-08-25 15:21:05

+0

這取決於你想要做的數據。如果它是針對單個行的簡單數據庫標誌更新,則通過JQuery連接的AJAX回調將是更好和更乾淨的方法。事實上,無論你對數據做什麼,它都可能是一個更清潔的方法。它將允許用戶更改多個複選框而無需回發。 – 2010-08-25 15:26:53

+0

這就是我最終做的。儘管如此,謝謝你的模型。它清楚地說明了它是多麼複雜,並引導我進入JQuery方向。 = D – Jason 2010-08-27 16:27:01

-1

你可以通過中繼器的每個項目使用onclick事件循環,並檢查每個複選框的值,(==器isChecked真)。

只要確保您不在中繼器上調用「DataBind()」,否則可能會導致問題。

+0

因此,如果我需要OnChange功能,我將不得不保留當前狀態的記錄?有沒有另一種方式? – Jason 2010-08-25 14:47:09

+0

當前狀態記錄在每個複選框的屬性中,所以除了循環通過每個複選框之外,您不應該做任何額外的操作。 – Brett 2010-08-25 21:00:02

2

試試這個隱藏代碼:

protected void Checked_Changed(object sender, EventArgs e) 
     { 
      var item = ((CheckBox)sender).Parent as RepeaterItem; 
// now you have the repeater row. You can travers further up the controls if you use Parent.Parent... 

     } 
相關問題