我用这个代码绑定一个组合框
List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
// Add data to the List
data.Add(new KeyValuePair<string, string>( "01","Bag"));
data.Add(new KeyValuePair<string, string>("02", "Box"));
data.Add(new KeyValuePair<string, string>("03", "Carton/Piece"));
data.Add(new KeyValuePair<string, string>("04", "Crate"));
data.Add(new KeyValuePair<string, string>("05", "Drum"));
data.Add(new KeyValuePair<string, string>("06","Pallet/Skid" ));
data.Add(new KeyValuePair<string, string>("07","Roll"));
data.Add(new KeyValuePair<string, string>("08", "Tube"));
// Clear the combobox
ddlPackageCode.DataSource = null;
ddlPackageCode.Items.Clear();
// Bind the combobox
ddlPackageCode.DataSource = new BindingSource(data, null);
ddlPackageCode.DisplayMember = "Value";
ddlPackageCode.ValueMember = "Key";
我可以从此代码中找到组合框中的选定值
KeyValuePair<string, string> selectedPair1 = (KeyValuePair<string, string>)ddlServiceCode.SelectedItem;
ShipmentConfirmReq.Shipment.Service.Code = selectedPair1.Key;
ShipmentConfirmReq.Shipment.Service.Description = selectedPair1.Value;
但是如何在组合框中设置所选值。我试试这个,但我收到错误NullReferenceException
。下面是我在组合框中设置所选值并获取错误的代码
KeyValuePair<string, string> selectedPair1 = (KeyValuePair<string, string>)cmbfield2.SelectedItem;
cmbfield2.SelectedValue = _commonEntity.Field2Value;