2013-12-16 62 views
0

請幫助我,我需要點擊按鈕觸發b_click過程,它不工作。 這是我的自定義控件,帶有一個GridView和一個使用ITemplate類動態添加的列。Gridview動態模板在自定義控件中沒有觸發事件

namespace NamespaceServerControlSearch 
{ 
    [ToolboxData("<{0}:ServerControlSearch runat=server></{0}:ServerControlSearch>")] 
    public class ServerControlSearch : CompositeControl 
    { 
     private global::System.Web.UI.WebControls.GridView grid; 


    protected override void CreateChildControls() 
    { 
     Controls.Clear(); 

     grid = new GridView(); 
     grid.AutoGenerateColumns = true; 
     grid.ID = "grid"; 
     grid.Width = Unit.Pixel(400); 
     grid.Height = Unit.Pixel(100); 
     grid.BorderStyle = BorderStyle.Solid; 

     DataColumn col = new DataColumn("xxx"); 
     TemplateField bfield = new TemplateField(); 
     bfield.HeaderTemplate = new GridViewTemplateSelect(ListItemType.Header, col.ColumnName); 
     bfield.ItemTemplate = new GridViewTemplateSelect(ListItemType.Item, col.ColumnName); 
     grid.Columns.Add(bfield); 

     DataSet ds = new DataSet(); 
     using (SqlConnection conn = new SqlConnection("Data Source=(local); Initial Catalog=casproduccion; USER=sa; PASSWORD=Jotsa123")) 
     { 
      SqlDataAdapter da = new SqlDataAdapter("select codigo, nombre from CAS_USERS cu where codigo like 'F37008%'", conn); 
      da.Fill(ds); 
     } 

     grid.DataSource = ds.Tables[0]; 
     grid.DataBind(); 

    } 

    protected override void Render(HtmlTextWriter o) 
    { 
     o.Write("<div style=\"width: 420px; height: 100px; overflow: scroll; border: 1px solid black;\">"); 
     grid.RenderControl(o); 
     o.Write("</div>"); 
    } 

    protected override void RecreateChildControls() 
    { 
     EnsureChildControls(); 
    } 
} 

public class GridViewTemplateSelect : Control, ITemplate 
{ 
    private ListItemType _templateType; 
    private string _columnName; 

    public GridViewTemplateSelect(ListItemType type, string colname) 
    { 
     _templateType = type; 
     _columnName = colname; 
    } 

    void ITemplate.InstantiateIn(System.Web.UI.Control container) 
    { 
     switch (_templateType) 
     { 
      case ListItemType.Header: 
       Label lbl = new Label(); 
       lbl.Text = _columnName; 
       container.Controls.Add(lbl); 
       break; 
      case ListItemType.Item: 

       Button b = new Button(); 
       b.Text = "test"; 
       //b.DataBinding += new EventHandler(b_click); 
       b.Click += new EventHandler(b_click); 
       container.Controls.Add(b); 
       break; 
     } 

    } 

    public void b_click(object sender, EventArgs e) 
    { 
     Button bb = (Button)sender; 
     bb.Text = bb.Text + "A";  //change name to test if it's receiving event 
     GridViewRow container = (GridViewRow)bb.NamingContainer; 
     string cid = container.Cells[1].Text; 

    } 
} 

}

回答

0

只是一個簡單的想法,但請更換線路:

b.Click += new EventHandler(b_click); 

由:

b.Click += b_click; 

加再上b_click函數添加細分,以確保該事件被解僱。 請讓我知道它是否適合你。

+0

感謝您的時間來閱讀我的問題,但它沒有奏效。 – Diego

相關問題