0

一般来说,我是 ASP.Net、C# 和 OOP 的新手,我正在尝试进入关于类、对象、方法等的正确范例。

我想DataTable从 Repeater.ItemDataBound 事件中访问一个。我将在哪里创建DataTable以便该方法可以访问它?我不希望每次调用 ItemDataBound 时都创建 DataTable,只创建一次。那会是一个单独的类,还是同一个类中的另一个方法,还是别的什么?

我想用它来HeaderTemplate设置Repeater. 这是我的代码:

public partial class test : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        int numPages = 3, numItems = 10;

        int[] parentRepeatCnt = Enumerable.Range(0, numPages).ToArray();
        int[] childRepeatCnt = Enumerable.Range(0, numItems).ToArray();

        ParentRepeater.DataSource = parentRepeatCnt;
        ParentRepeater.DataBind();

        foreach (int i in parentRepeatCnt)
        {
            Repeater ChildRepeater = ParentRepeater.Items[i].FindControl("ChildRepeater") as Repeater;
            ChildRepeater.DataSource = childRepeatCnt;
            ChildRepeater.DataBind();
        }
    }

    public void ChildRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            Label Label1 = e.Item.FindControl("Label1") as Label;
            // access DataTable here
            Label1.Text = myDataTable.Rows[0]["item"].ToString();
        }

    }
}

另外,请随时批评我现有的代码。谢谢!

4

1 回答 1

0

公共部分类测试:System.Web.UI.Page {

公共数据表 mydatatable = 新数据表();

protected void Page_Load(object sender, EventArgs e)
{
    int numPages = 3, numItems = 10;

    int[] parentRepeatCnt = Enumerable.Range(0, numPages).ToArray();
    int[] childRepeatCnt = Enumerable.Range(0, numItems).ToArray();

    ParentRepeater.DataSource = parentRepeatCnt;
    ParentRepeater.DataBind();

    foreach (int i in parentRepeatCnt)
    {
        Repeater ChildRepeater = ParentRepeater.Items[i].FindControl("ChildRepeater") as Repeater;
        ChildRepeater.DataSource = childRepeatCnt;
        ChildRepeater.DataBind();
    }
}

public void ChildRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        Label Label1 = e.Item.FindControl("Label1") as Label;
        // access DataTable here
        Label1.Text = myDataTable.Rows[0]["item"].ToString();
    }

}

}

于 2012-12-25T05:35:14.223 回答