简体   繁体   English

列表框未显示任何结果

[英]listbox not showing any results

I want my listbox in visual studio to list the courses in my course table (from the database) the application runs fine but the listBox remains empty this is the code I'm using: 我希望Visual Studio中的列表框列出课程表中的课程(来自数据库),应用程序运行良好,但listBox仍然为空,这是我正在使用的代码:

  protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sqlcon = "Data Source = localhost; Persist Security Info = True; User ID = localhost; Password = ****; Unicode = True";

        OracleConnection con = new OracleConnection(sqlcon);
        con.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = con;
        cmd.CommandText = "select coursename from course";
        cmd.CommandType = CommandType.Text;
        OracleDataReader dr = cmd.ExecuteReader();
        dr.Read();

        while(dr.Read())
        {
            ListBox1.Items.Add(dr.GetString(1));
        }
    }

There are at leat three errors in your code and some logic problem. 您的代码中至少有三个错误和一些逻辑问题。

Errors first: 错误优先:

  • You call read without doing anything with the record loaded by the read. 您无需对读取的记录进行任何操作即可调用read。
  • When you reach the loop code you have already loaded the first record, so the Read inside the while just try to load the second record. 当您到达循环代码时,您已经加载了第一条记录,因此“读入内部”仅尝试加载第二条记录。 But if there is just one record the loop never runs and thus there are no items in the list 但是,如果只有一条记录,则循环永远不会运行,因此列表中没有项目
  • You call GetString(1) but you retrieve just the coursename from the table and this will give an exception for index out of range. 您调用GetString(1),但只从表中检索课程名称,这将为索引超出范围提供例外。 Arrays start at index zero so to get the coursename you need GetString(0) 数组从索引零开始,因此要获取课程名,您需要GetString(0)

     // Not needed, let the loop run // dr.Read(); while(dr.Read()) { // The first column is at index zero ListBox1.Items.Add(dr.GetString(0)); } 

Finally the logic problem. 最后是逻辑问题。 It seems that you use the SelectedIndexChanged event to fill the items of the same list that triggers the SelectedIndexChanged. 似乎您使用SelectedIndexChanged事件来填充触发SelectedIndexChanged的同一列表的项目。 This seems to be illogic because you have already items in that list and selecting one triggered the event. 这似乎是不合逻辑的,因为您已经在该列表中有项目并选择一个项目触发了该事件。 This code should be run somewhere else (The Load event?) What are you trying to do here? 这段代码应该在其他地方运行(Load事件?)您要在这里做什么? Anyway, if you really want to keep this code then you should at least clearing the Items collection before loading items from the database otherwise, at each SelectedIndexChanged you add another set of item identical to the already loaded one. 无论如何,如果您确实想要保留此代码,则至少应在从数据库加载项目之前清除Items集合,否则,在每个SelectedIndexChanged处添加与已加载的项目相同的另一组项目。

  // Before filling the items clear the previous ones
  listBox1.Items.Clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM