简体   繁体   中英

drop down list with value from database

I am new to C# asp.net web form, search all the tread, but i did not have a answer.

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; //read from web.config.
SqlConnection con = new SqlConnection(constr);
DataTable dt = new DataTable();
con.Open();
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select * from gender", con);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
    ddlmarrital.DataSource = myReader;         //assigning datasource to the dropdownlist
    ddlmarrital.DataTextField = "field";       // text field name of table dispalyed in dropdown
    ddlmarrital.DataValueField = "ID";         // to retrive specific  textfield name 
    ddlmarrital.DataBind();                    //binding dropdownlist
}
con.Close();

table1 (Gender) 1.male 2.female.

Mastertable1 (Name "ABC").(Gender "Male).(Address "ABC")

I want to display a value (Mastertable1.gender) that saved, and if i want to change the value i can use the dropdownlist to select.

Dropping a SqlDataSource object on the web form from the ToolBox would be more easy. Set the Dropdownlist to the sqldatasource object and configure the sqldatasource.

If you must do it in code, remove your while loop.

...
myReader = cmd.ExecuteReader();
ddlmarrital.DataSource = myReader;                 
ddlmarrital.DataTextField = "field";
ddlmarrital.DataValueField = "ID";
ddlmarrital.DataBind();
con.Close();

You could try something like the following. I refactored a bit your code and I use the using statement for both SqlConnection and SqlCommand objects, because they both implement the IDisposable interface. Specifically, they use unmanaged resources and this resources, which should be released as soon as possible after you have done your job with them. This is why the Dispose method should be called. A convenient way to do so is to use the using statement, like below.

string connectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 

using(var connection = new SqlConnection(connectionString))
{
    connection.Open();

    var commandText = "SELECT * FROM gender";

    using(var command = new SqlCommand(commandText,connection))
    {
        ddlmarrital.DataSource = command.ExecuteReader();
        ddlmarrital.DataTextField = "field";       
        ddlmarrital.DataValueField = "ID";  
        ddlmarrital.DataBind();         
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM