Databind a dropdownlist

前端 未结 4 2048
梦毁少年i
梦毁少年i 2020-12-03 18:39

When I try to databing dropdownlist, got this: system.data.datarowview
what do I wrong?

 string strQuery = \"Select Item FROM         


        
4条回答
  •  情书的邮戳
    2020-12-03 19:22

    You need to tell it what fields to use as value and text.

    ddlList.DataSource = sqlTa;
    ddlList.DataValueField = "ValueField";
    ddlList.DataTextField = "TextField";
    ddlList.DataBind();
    

    And your select statement is missing a ". It should be:

    "Select Item FROM Calendar Where UserD='Test'"
    

    An Example being:

    As ryan pointed out if you are pulling back one field then you can just do:

            DataTable dtTable = new DataTable();
    
            try
            {
                using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
                {
                    using (SqlCommand sqlCommand = new SqlCommand("Select Item FROM Calendar Where UserD='Test'", sqlConnection))
                    {
                        sqlConnection.Open();
    
                        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                        {
                            dtTable.Load(sqlDataReader);
                            sqlDataReader.Close();
                        }
                    }
                }
            }
            catch (Exception error)
            {
                throw error;
            }
    
            ddlList.DataSource = dtTable;
            ddlList.DataBind();
    

    But if you have more then one field then you can do this:

            DataTable dtTable = new DataTable();
    
            try
            {
                using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
                {
                    using (SqlCommand sqlCommand = new SqlCommand("Select Item, id FROM Calendar Where UserD='Test'", sqlConnection))
                    {
                        sqlConnection.Open();
    
                        using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                        {
                            dtTable.Load(sqlDataReader);
                            sqlDataReader.Close();
                        }
                    }
                }
            }
            catch (Exception error)
            {
                throw error;
            }
    
            ddlList.DataSource = dtTable;
            ddlList.DataValueField = "id";
            ddlList.DataTextField = "item";
            ddlList.DataBind();
    

提交回复
热议问题