【问题标题】:Unable to add into ArrayList then in Listbox C#无法添加到 ArrayList 然后在 Listbox C#
【发布时间】:2014-09-26 04:24:17
【问题描述】:

想要将数组列表中的值循环到列表框中。目前,只有 arraylist 中的最新项被添加到列表框中。

按钮下的代码

                string strRating = txtRatingComment.Text;
                string strReturnedFilePath = db.retrievePictureRating(strRating);
                //clear album
                listBoxSearchResult.Items.Clear();

                //Add filepaths into arraylist
                pictureList.Add(strReturnedFilePath);

                //Loop arraylist into listbox
                for (int i = 0; i < pictureList.Count; i++)
                {
                    listBoxSearchResult.Items.Add(pictureList[i]);
                }

Database类下的代码

 public string retrievePictureRating(string strRating)
    {
        string query = "SELECT pictureFilePath FROM picture where pictureRating = @pictureRating;";
        string pictureFilePath = "";

        //open connection
        if (this.OpenConnection() == true)
        {
            //Create Command
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@pictureRating", strRating);

            //Create a data reader and Execute the command
            MySqlDataReader dataReader = cmd.ExecuteReader();

            //Read the data and store them in the list
            while (dataReader.Read())
            {
                pictureFilePath = dataReader["pictureFilePath"].ToString();
            }
            //close Data Reader
            dataReader.Close();

            //close Connection
            this.CloseConnection();
        }
        return pictureFilePath;
    }

【问题讨论】:

    标签: c# database arraylist listbox


    【解决方案1】:

    在这一行中创建一个变量:

    string pictureFilePath = "";
    

    然后在循环中你总是将值分配给同一个变量:

    while (dataReader.Read())
    {
        pictureFilePath = dataReader["pictureFilePath"].ToString();
    }
    

    所以你总是将值赋给同一个变量,所以只剩下最后一行。您需要创建一个列表来获取所有值,而不仅仅是最后一个。

    【讨论】:

    • 除此之外,即使您的 retrievePictureRating 方法的签名也表明它返回一个字符串。
    【解决方案2】:

    我认为问题出在这里:

    pictureFilePath = dataReader["pictureFilePath"].ToString();
    

    这将覆盖函数从该循环中读取的任何其他字符串。您需要让您的函数返回一个字符串数组,然后添加它们。目前,您创建的数组“图片列表”仅包含一个字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-08
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      相关资源
      最近更新 更多