2012-10-25 40 views
1

所以我有一个嵌套类--PeerReviews。我想创建一个ASPX页面上的列表框,和我实例化,像这样PeerReviews的对象:非静态字段需要对象引用

PeerReviews obj = new PeerReviews(); 

不过,我得到一个错误,该行导致我的代码问题:

listBox1.Items.Add(new ListItem(r["first_name"], r["first_name"])); 

这里是嵌套类的全码:

class PeerReviews 
     { 
      private static void PeerReview() 
      { 


       MySqlConnection con = new MySqlConnection("server=localhost;database=hourtracking;uid=username;password=password"); 
       MySqlCommand cmd = new MySqlCommand("select first_name from employee where active_status=1", con); 
       con.Open(); 
       MySqlDataReader r = cmd.ExecuteReader(); 

       while (r.Read()) 
       { 
        listBox1.Items.Add(new ListItem(r["first_name"], r["first_name"])); 
       } 
       con.Close(); 


      } 
     } 

我如何引用列表框中的项目?我试图将它实例化为一个对象(这看起来不正确)。

我只是OOP编程而已(我已经完成了一些工作,但是我在C#中工作的原因之一就是强迫自己使用它),而且我几乎完整新手到C#和ASP.NET

编辑:

这是ASPX代码:

<asp:ListBox ID="listBox1" runat="server"> 
</asp:ListBox> 
+0

被listBox1中在asp侧代码设置为RUNAT = “服务器”? – Haedrian

+0

我不认为这是行 - 再次检查 – codingbiz

+1

你也有内存泄漏,你需要将你的连接,命令和阅读器对象封装在'using'语句中。 – JonH

回答

2

我认为你需要删除的PeerReview功能static关键字。

+0

然后发生这种情况: 编译器错误消息:CS0038:无法通过嵌套类型'commenter.PeerReviews' –

+0

访问外部类型'commenter'的非静态成员是否意味着我只需要实例化PeerReviews的对象? –

0

将引用listbox1的对象传递给静态PeerReview方法。类的静态方法不能访问其类或任何其他类的静态字段/属性/方法。它只能访问其他静态类字段/属性/方法,局部变量和参数

你需要类似的东西(我不确定System.Web.UI.Page的实例是否保存listBox1,但我正在寻求)

private static void PeerReview(System.Web.UI.Page page) 
{ 
//... 
page.listBox1.Items.Add(new ListItem(r["first_name"], r["first_name"])); 
//... 
} 

或作为Rawling Sayed的:

private static void PeerReview(System.Web.UI.WebControls.ListBox listbox) 
    { 
    //... 
    listbox.Items.Add(new ListItem(r["first_name"], r["first_name"])); 
    //... 
    } 
+0

它必须是当前页面的类型。或者您可以改为使用列表框本身。 – Rawling

相关问题