Click here to Skip to main content
15,909,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello.
I intend to bind my dropdownlist to sqlserver and read the items(CityName)that i have them in DB(Table City)and then list and fill them into the dropdownlist.
for this matter i have written the code below in Page_load that whenever i start to debug all city items to be seen in dropdownlist:

C#
protected void Page_Load(object sender, EventArgs e)
       {
           SqlConnection conn = new SqlConnection();
           SqlCommand cmd = new SqlCommand();
           conn.ConnectionString = ConfigurationManager.ConnectionStrings["PersonTest"].ConnectionString;

           conn.Open();
           cmd.CommandText = "SELECT CityName FROM City";
           cmd.Parameters.Add("@CityName", SqlDbType.NVarChar).Value = DropCity.AppendDataBoundItems;
           cmd.ExecuteReader();
           conn.Close();
       }


but in line (cmd.ExecuteReader();) this error occurs:

InvalidOperationException was unhandled by user code.
ExecuteReader: Connection property has not been initialized

meanwhile i know that i can use ASP.net DataBinding(by wizard)ability, but i want to do it with myself . and also i don't know which one is better to be used in forms? which one do you suggest to use?
Posted
Comments
JakirBB 22-Jul-12 2:54am    
Did you make any relation between cmd and conn in your code?
JakirBB 22-Jul-12 3:00am    
Which connection will be used by cmd. Why have you add parameters though in SQL there is no use of?

1 solution

Hi ,
you can use this for bind data to your dropdownlist
C#
if (!IsPostBack)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PersonTest"].ConnectionString))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT CityName , id FROM City", conn))
            {
                DataTable dt = new DataTable();
                SqlDataAdapter adpt = new SqlDataAdapter(cmd);
                adpt.Fill(dt);
                DropCity.DataTextField = "CityName";
                DropCity.DataValueField = "id";
            }
        } 
    }

and for select the value of dropdownlist you can use SelectedValue
Best Regards
M.Mitwalli
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900