如何将控件访问到类中?

时间:2011-01-26 10:36:47

标签: asp.net

我在page.aspx中有一个Gridview。这个gridview我想作为参数传递给class1.cs.Can的构造函数任何人都可以打电话给我,如何做到这一点?

1 个答案:

答案 0 :(得分:1)

所以你有一个带有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。

希望这就是你所要求的; - )