C#中数据库中的空dropdownlist

本文关键字:dropdownlist 数据库 | 更新日期: 2023-09-27 18:21:17

我正在处理一个遗留代码,但我被一个空的DropDownList卡住了。这是代码:

private void CarregarCheckboxPesquisas()
    {
        string sqlConexaoString = ConfigurationManager.ConnectionStrings["Sql_Interno"].ConnectionString;
        SqlConnection sqlConexao = new SqlConnection(sqlConexaoString);
        ArrayList listaPesquisas = new ArrayList();
        ArrayList listacodPesquisas = new ArrayList();
        listaPesquisas.Add("Selecione uma pesquisa");
        listacodPesquisas.Add("");

        try
        {
            string sqlComandoString = "SELECT codPesquisa, titulo FROM Pesquisas ORDER BY codPesquisa DESC;";
            SqlCommand sqlComando = new SqlCommand(sqlComandoString, sqlConexao);
            sqlConexao.Open();
            SqlDataReader dr1 = sqlComando.ExecuteReader(CommandBehavior.CloseConnection);
            while (dr1.Read())
            {
                listacodPesquisas.Add(dr1.GetString(0));
                listaPesquisas.Add(dr1.GetString(1));
            }
            dr1.Close();
            sqlConexao.Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("########## Erro na obtenção dos valores das questões: " + ex.Message.ToString());
        }
        for (int i = 0; i < listacodPesquisas.Count; i++)
        {
            ListItem li = new ListItem(listaPesquisas[i].ToString(), listacodPesquisas[i].ToString());
            DDLPesquisa.Items.Add(li);
            //DDLPesquisa.Items.Add(new ListItem(listaPesquisas[i].ToString, listacodPesquisas[i].ToString()));
        }
    }

我已经检查了SQL连接,它运行良好。所以,我想它一定是别的东西,但我没能发现是什么。我做了研究,但还是一无所获。

有什么想法吗?

C#中数据库中的空dropdownlist

这里的想法很简单,所以不要批评我,但你确定listacodPesquisas不是空的吗。在将列表添加到下拉列表之前,请查看是否可以输出该列表。它还会给你一个错误还是只是显示为空?

试着给它一个indexitems.Insert,就像这个一样

DDLPesquisa.Items.Insert(0,li);

或者你也可以通过这种方式绑定你的下拉列表:

try
    {
        string sqlComandoString = "SELECT codPesquisa, titulo FROM Pesquisas ORDER BY codPesquisa DESC;";
        SqlCommand sqlComando = new SqlCommand(sqlComandoString, sqlConexao);
        sqlConexao.Open();
        DDLPesquisa.DataSource = sqlComando.ExecuteReader();
        DDLPesquisa.DataTextField = "titulo";
        DDLPesquisa.DataValueField = "codPesquisa";
        DDLPesquisa.DataBind();
        sqlConexao.Close();
    }
    catch (Exception ex)
    {
        Debug.WriteLine("########## Erro na obtenção dos valores das questões: " + ex.Message.ToString());
    }