页面Page_Load事件与Repeater ItemCommand [英] The Page Page_Load Event Vs The Repeater ItemCommand

查看:61
本文介绍了页面Page_Load事件与Repeater ItemCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Page_Load中运行一些代码,然后将这段代码的结果存储在一些局部变量中.

I'm running some code in Page_Load then I store the results from this code in some local variables.

现在我使用此局部变量将其分配给我的转发器项目模板内的控件

Now I use this local variables to assign them to the controls inside my repeater item template

问题是>>页面未显示项目模板,但没有数据绑定..我认为转发器无法在Page_Load中加载分配给它的数据,并且它已初始化-与生命周期相关问题-

The Problem Is >> the page doesn't displays the item template but there's no data bound to it..I think the repeater can't load the data assigned to it in the Page_Load and it get's initialized -life cycle related issues-

任何想法到底是什么问题?以及如何解决这个问题?

Any idea what the problem is exactly ? and how to solve this ?

编辑

一些示例代码:

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

        int UserId = 0;

        protected void Page_Load(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);

            SqlCommand comm = new SqlCommand("SELECT * From Users, conn);
            SqlDataReader reader;

            conn.Open();
            reader = comm.ExecuteReader();

//I'm not sure if I need those two lines:
            AllBrandsRptr.DataSource = reader;
            AllBrandsRptr.DataBind();

            while (reader.Read())
            {

                    UserId = (int)reader["UserId"];
            }
                conn.Close();

            }
        }


    protected void AllBrandsRptr_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

        Label LabelTest = (Label)e.Item.FindControl("MyTestLabel");
        LabelTest.Text = UserId.ToString();

    }

编辑2

我的Sql SELECT语句

My Sql SELECT Statement

string command1 = "SELECT Brands.BrandId, Brands.BrandName, Brands.BrandLogo, Brands.BrandWebsite, Brands.IsBrandVisible, Cuisines.CuisineType, VenueTypes.VenueTypeName FROM         Brands FULL OUTER JOIN BrandCuisines ON BrandCuisines.BrandId = Brands.BrandId FULL OUTER JOIN Cuisines ON Cuisines.CuisineId = BrandCuisines.CuisineId FULL OUTER JOIN BrandVenueTypes ON BrandVenueTypes.BrandId = Brands.BrandId FULL OUTER JOIN VenueTypes ON VenueTypes.VenueTypeId = BrandVenueTypes.VenueTypeId";

我的过滤代码

            conn.Open();
            reader = comm.ExecuteReader();
            AllBrandsRptr.DataSource = reader;
            AllBrandsRptr.DataBind();

            while (reader.Read())
            {

                  if (((int)reader["BrandId"]) == BrandId) //this line to pass collecting some info, if I already iterated through the same Id 
                  {
                    BrandId = (int)reader["BrandId"];
                    BrandName = (string)reader["BrandName"];
                    BrandLogo = (string)reader["BrandLogo"];
                    BrandWebsite = (string)reader["BrandWebsite"];
                    IsVisible = (bool)reader["IsBrandVisible"];
                  }

                if (reader["CuisineType"] != DBNull.Value)
                {
                    Cuisines += (string)reader["CuisineType"];
                }

                if (reader["VenueTypeName"] != DBNull.Value)
                {
                    VenueTypes += ", " + (string)reader["VenueTypeName"];
                }

                conn.Close();

我的最初问题

推荐答案

您根本不应该手动遍历DataReader.它是仅前进的工具.只有Repeater while循环可以迭代结果.我认为您面临的直接问题是,在Repeater呈现之前,while循环耗尽了DataReader.

You shouldn't manually iterate over the DataReader at all. It is a forward-only tool. Only the Repeater or your while loop may iterate through the results. I believe your immediate problem is that your while loop is exhausting the DataReader before the Repeater renders.

当调用 DataBind()时,您正在指示Repeater为分配给其作为 DataSource 的集合中的每个项目呈现其模板.因此,任何过滤都需要在此之前进行.理想情况下,您可能应该将该过滤逻辑作为 where 子句添加到SQL语句中.

When you call DataBind(), you're instructing the Repeater to render its template for every item in the collection you assigned as its DataSource. So, any filtration would need to happen before. Ideally, you should probably add that filtration logic as a where clause to your SQL statement.

您能更具体地说明您要解决的实际问题吗?否则很难为您提供准确的建议.

Can you be more specific about the real problem you're trying to solve? It's hard to give you accurate advice otherwise.

更新:

请记住, while(reader.Read())不能像事件处理程序那样工作,或者与它在语义上听起来的方式类似.换句话说,您并不是在读取DataReader时告诉程序做某事,而是在告诉它立即开始读取数据(与Repeater无关).

Keep in mind that while(reader.Read()) does not work like an event handler or otherwise similar to how it might semantically sound. In other words, you aren't telling the program to do something when the DataReader is read, you're telling it to start reading through the data immediately (unrelated to the Repeater).

这是我建议您尝试的:

string sql = "Your current SQL here";
string connectionString = "Your connection string here";

// The using block ensures that the connection will be closed and freed up,
//  even if an unhandled exception occurs inside the block.
using (SqlConnection conn = new SqlConnection(connectionString))
{
  SqlCommand cmd = new SqlCommand(sql, conn);

  SqlDataAdapter da = new SqlDataAdapter(cmd);

  DataTable dt = new DataTable();

  da.Fill(dt);

  AllBrandsRptr.DataSource = dt;
  AllBrandsRptr.DataBind();

  var cuisineTypes = from row in dt.AsEnumerable()
                     select row["CuisineType"];

  string cuisines = string.Join(", ", cuisineTypes.Distinct());

  var venueTypes = from row in dt.AsEnumerable()
                   select row["VenueTypeName"];

  string venues = string.Join(", ", venueTypes.Distinct());
}

通过使用DataTable而不是DataReader,您可以根据需要遍历数据多次.DataReader的性能更高,如果只需要一次仅向前读取的数据,但是DataTable的功能要强大得多,并且在这些情况下对DataReader来说是无能为力的.

By using a DataTable instead of DataReader, you're able to iterate through the data as many times as necessary. The DataReader is more performant, if a single, forward-only read through the data is all you need, but the DataTable is much more powerful and is helpful in these situations beyond the DataReader's capabilities.

值得一提的是,如果您长期关心此项目并希望使其可维护,则应考虑最终将其中一些数据访问代码移至单独的层.您应该努力避免在.aspx.cs文件中使用SQL语句或直接数据访问代码.

It's worth mentioning that if you care about this project in the long-term and want to make it maintainable, you should consider eventually moving some of this data access code to a separate layer. You should strive to never have SQL statements or direct data access code in your .aspx.cs files.

然后,您在Page_Load中的代码可以被强类型化并更易于使用:

Then, your code in Page_Load could be strongly typed and easier to work with:

List<Brand> brands = Brand.GetAllBrands();

AllBrandsRptr.DataSource = brands;
AllBrandsRptr.DataBind();

var cuisineTypes = from brand in brands
                   select brand.CuisineType;

string cuisines = string.join(", ", cuisineTypes.Distinct());

var venueTypes = from brand in brands
                 select brand.VenueType;

string venues = string.join(", ", venueTypes.Distinct());

这篇关于页面Page_Load事件与Repeater ItemCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆