1

現在、C# でコンボボックスから値を取得するのに苦労しています。コンボボックスの項目はデータベースから取り込まれます。これは私がアイテムを埋める方法です:

while (reader.Read())

                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = (string)reader[0];
                    item.Value = (string)reader[1];
                    comboBox8.Items.Add(item);

                }

このコマンドはテキストを表示しますが、値は表示しません:

String s = comboBox8.SelectedItem.ToString();

このコマンドは「System.NullReferenceException」をスローします

String s = comboBox8.SelectedValue.ToString();
4

3 に答える 3

3

SelectedValue プロパティは、ComboBox をデータ ソースにリンクしており、表示されている値以外の値を返したい場合に使用します。

たとえば、1 つの代替手段として、DataTable を作成し、データベースの読み取り値をそこに入れ、コンボボックスで選択した値とテキストをそこに割り当てます。例えば;

DataTable dataTable = new DataTable();
//column 1 name, which will be display member
dataTable.Columns.Add(new DataColumn("nameOfYourTextField"); 
//column 2 name, which will be your value member
dataTable.Columns.Add(new DataColumn("nameOfYourValueField"); 

//assign your datasource (the datatable) to the combobox
comboBox8.DataSource = dataTable; 

//and finally assign your value member (the text you want returning)
comboBox8.ValueMember = "nameOfYourValueField";
//and your display member (the text visible in the combobox)
comboBox8.DisplayMember = "nameOfYourTextField";

次に、リーダーで;

while (reader.Read())

            { 
                //create a new row which matches the signature of your datatable
                DataRow row = dataTable.NewRow();
                //assign data to the rows, given a certain column name
                row["nameOfYourValueField"] = reader[1];
                row["nameOfYourTextField"] = reader[0];
                //and add the row to the datatable
                dataTable.Rows.Add(row);

            }
于 2013-04-11T13:09:32.937 に答える
0

この方法も試すことができます。

コンボボックスをバインドした後、次を設定する必要があります。

 comboBox8.ValueMember = "DBFieldName1";
 comboBox8.DisplayMember = "DBFieldName2";

 if(comboBox8.SelectedItem != null)
 {
        string text=comboBox8.SelectedItem.ToString();
        string value=comboBox8.SelectedValue.ToString();
 }

注 : - また、リーダーが null 値または繰り返し値を返さないようにしてください。

お役に立てれば :)

于 2013-04-11T13:05:18.590 に答える