MarlonPereira
MarlonPereira

Reputation: 13

Empty dropdownlist from database in C#

I'm working on a legacy code, and I'm stuck with a DropDownList that's empty. Here's the code:

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()));
        }

    }

I already checked the SQL connection, it's working fine. So, I assume it must be something else, but I failed at discovering what. I did my research, and still nothing.

Any thoughts?

Upvotes: 0

Views: 77

Answers (2)

Syed Ali Taqi
Syed Ali Taqi

Reputation: 4974

Try giving it an index and also items.Insert like this

DDLPesquisa.Items.Insert(0,li);

Or you can also Bind your DropDownList this way:

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());
    }

Upvotes: 0

Diesel298
Diesel298

Reputation: 21

Kinda thinking simple here so dont criticize me but are you sure listacodPesquisas is not empty or null. See if you can output the list before you add it to the drop down. Also does it give you an error or just shows empty?

Upvotes: 1

Related Questions