2016-03-19 7 views
0

私はC#asp.net Webフォームを初めて使用していますが、すべてのトレッドを検索しますが、回答はありませんでした。データベースから値をドロップダウンリスト

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(性別)1.male 2.female。

Mastertable1(名称 "ABC")。(性別「男性)。(アドレス "ABC")

私が保存された値(Mastertable1.gender)を表示したい、と私は値を変更したい場合私が選択するためにドロップダウンリストを使用することができます。ツールボックスからWebフォーム上のSqlDataSourceオブジェクトをドロップ

+0

ループを削除します。しかし、問題は何ですか? – Steve

+0

"Mastertable1" .genderの値をドロップダウンリストに表示することができません。 – sakura

+0

しかし、MasterTableの値が必要な場合は、なぜGenderテーブルをクエリしますか? – Steve

答えて

0

がより簡単だろう。SqlDataSourceコントロールオブジェクトにドロップダウンリストを設定し、SqlDataSourceコントロールを設定します。

をあなたがそれを行う必要がある場合コード、whileループを削除してください。

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

次のようなものを試すことができます。私はあなたのコードを少しリファクタリングしました。とSqlCommandオブジェクトの両方にusingステートメントを使用しています。これらのオブジェクトは両方ともIDisposableインターフェイスを実装しているためです。具体的には、管理されていないリソースとこのリソースを使用します。これらのリソースは、仕事をした後できるだけ早くリリースする必要があります。このため、Disposeメソッドを呼び出す必要があります。これを行う便利な方法は、以下のようにusingステートメントを使用することです。

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

ありがとうChristos、dropdownlistの仕事ですが、Mastertable1(Gender "Male")をデフォルト値として表示する方法を設定するにはどうすればいいですか? – sakura

+0

私はあなたを知りません。あなたが探しているものをもっと徹底的に説明する必要があります。 – Christos

+0

Mastertable1の値を持つドロップダウンリストが必要です。完全に間違っている – sakura

関連する問題