Connecting DropDownList to mysql in asp.net using c#

I created aboutcodes data base having reportcard table as show below



If I want to make subject column to load in DropDownList than use below function and call subjectname() Function in Page_Load Function

Here DropDownList1 is Id of DropDownList

public void subjectname()
        {
            string MyConString = "SERVER=localhost;" +
                       "DATABASE=aboutcodes;" +
                       "UID=root;" +
                       "PASSWORD=;";

            /* speed is database name, root is mysql username, test is mysql password */

            using (MySqlConnection connection = new MySqlConnection(MyConString))
            {
                MySqlCommand command = connection.CreateCommand();
                try
                {
                    // open connection
                    connection.Open();
                    // reportcard is mysql table name

                    string cmdText = "SELECT * FROM  `reportcard` ";

                    MySqlCommand cmd = new MySqlCommand(cmdText, connection);

                    MySqlDataReader ddlValues;
                    ddlValues = cmd.ExecuteReader();

                    //subject is column name

                    DropDownList1.DataSource = ddlValues;
                    DropDownList1.DataValueField = "subject";
                    DropDownList1.DataTextField = "subject";
                    DropDownList1.DataBind();
                    //close connection
                    connection.Close();
                }
                catch
                {

                    Label1.Text = "Error In Connection";


                }
            }//end of use of use

        }

One Comment

  1. Nice article. I feel that u can do it a touch better as this is connected architecture.
    import a dll file called microsoft.applicationblocks.data
    and instead of string cmdText = "SELECT * FROM `reportcard` MySqlCommand cmd = new MySqlCommand(cmdText, connection);
    MySqlDataReader ddlValues;
    ddlValues = cmd.ExecuteReader();
    u can use
    dataset ds=sqlhelper.executedataset(connectionname,"Query");

    ReplyDelete

Add your comments here

Back to Top