我如何访问一个控件到一个类中?

问题描述:

我在page.aspx中有一个Gridview。这个gridview我想作为参数传递给class1.cs.的构造函数。任何人都可以打电话给我,这怎么办?我如何访问一个控件到一个类中?

+0

哪个GridView的?或者这不是asp.net mvc? – alexn 2011-01-26 10:38:29

所以,你有一个网页,一个GridView:

<asp:GridView runat="server" ID="gv1" AutoGenerateColumns="true"> 
</asp:GridView> 

<div> 
    This is where the count of rows of your GridView will be displayed: 
    <p> 
     <strong><asp:Label runat="server" ID="lCount" /></strong> 
    </p> 
</div> 

而且,在代码隐藏你填充它是这样的:

this.gv1.DataSource = FullName.GetDemoCollection(); //Just returns a List<string>; 
gv1.DataBind(); 

和你有另一个类GridViewRowCounter做一些事GridView,例如计算行:

public class GridViewRowCounter 
{ 
    private System.Web.UI.WebControls.GridView _gv; 

    public GridViewRowCounter(){} 

    public GridViewRowCounter(System.Web.UI.WebControls.GridView _GV){ 
     this._gv = _GV; 

    } 

    public int GetRowCount(){ 
     return _gv.Rows.Count; 
    } 

} 

所以,你的GridView传递给Gridviewcounter类,你可以这样做:

public partial class PassingControls : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     //Bind the GridView 
     this.gv1.DataSource = FullName.GetDemoCollection();// 
     gv1.DataBind(); 

     //Pass Gridview reference to the GridVeiwRowCounter constructor. 
     GridViewRowCounter gvcounter = new GridViewRowCounter(this.gv1); 
     //Get the external class to return the rowcount from your GridView. 
     this.lCount.Text = gvcounter.GetRowCount().ToString(); 
    } 
} 

HTH。

希望这是你问;-)

+0

感谢花时间回答我,但是,对不起! ü误解了我的问题。:-)其实我想传递的GridView作为参数的一类事情是这样的MyClass类 { 公共MYCLASS(GridView的GV) {// 一些代码 } }上面的代码需要在一个班上。 Gridview我想从.aspx页面传递。我想一些命名空间必须添加到类中,以在构造函数中将gridview作为数据类型。这个怎么做? – Swathi 2011-01-28 04:47:30