0

请帮助我以不同的标签显示数据库中选定的列数据。

protected void Page_Load(object sender, EventArgs e)
{
    con.Open();       
        MySqlCommand countcmd = new MySqlCommand("select count(*) from category", con);
        int temp = Convert.ToInt32(countcmd.ExecuteScalar().ToString());
        MySqlCommand inscmd = new MySqlCommand("select catname from category where cid > 0", con);
        string temp1 = inscmd.ExecuteScalar().ToString();
        MySqlDataReader dr = inscmd.ExecuteReader();
        dr.Read();
        for (int i = 0; i < temp; i++){
            ("label" & i).text = dr[i].ToString();
        }       
}
4

2 回答 2

0

使用页面 FindControl 方法 http://msdn.microsoft.com/en-us/library/31hxzsdw.aspx

于 2013-08-09T14:05:22.920 回答
0

一开始那是完全错误的,你不能用 (string).Text 访问控件。

下一个问题是什么是创建这些标签,如果它们是在设计时预先创建的,你怎么知道你有足够的,你打算如何处理额外的?

PS您应该为每个查询建立一个新的连接,并让连接池处理缓存而不是传递一个实例化的一轮,除非在极少数情况下。

您还应该处理您的查询对象,使用对这个有好处,而不是在您开始耗尽内存时依靠 GC 进行整理。

此外,您的查询返回一列的行,因此您需要一个 while 循环。

我要做的第一件事是IEnumerable<String>从查询中返回一个。

例如类似的东西

private IEnumerable<String> GetCategoryNames(String argConnectionString)
{
   using(SqlConnection con = new SqlConnection(argConnnectionString))
   {
       con.Open()
       using(SqlCommand com = new SqlCommand("Select CatName From Category Where cid > 0", con))
       {
           using(SqlDataReader reader = com.ExecuteReader())
           {
              while (reader.Read())
              {
                  yield reader[0].ToString();
              }
           }
       }
   }
}

然后我会敲出一些可以滚动和实例化标签的东西

private void AddNewLabels(argConnectionString)
{
  int count = 0;
  Point startPoint = new Point(0,0) // assuming this is where you want the first label to be in the scroll box
  labelSpacing = 20; // how far apart vertically should your column of labels be.
  foreach(String labelText in GetCatgoryNames(argConectionString))
  {
      Label label = new Label();
      label.parent = myScrollBox;
      label.Left = StartPoint.X;
      label.Top = Count * LabelSpacing + StartPoint.Y;
      label.Name = String.Concat'MyDynamicLabel'
      // etc
      label.Text = labelText;
      count++;
  }
}

protected void Page_Load(object sender, EventArgs e)
{
   DestroyPreviousLabels();
   AddNewLabels(conn.ConnectionString);
}

DestroyNewLabels 将使用FindControl, 来查找名称以“MyDynamicLabel”开头的控件。或者你可以变得更聪明一些,只摧毁你不需要的,只在你需要的时候创造更多。如果您想这样做,请考虑 aList<Label>并从中添加和删除,然后您将计算一个循环,并且您不必继续寻找它们,因为这不是明智的表现。

无论如何,一些想法和一些重构机会,一旦你开始工作。

注意,这不是我的想法,所以可能是一两个傻瓜。

于 2013-08-09T14:36:37.707 回答