我已尝试使用以下代码将组合框的选定值添加到文本框但它会给我以下错误
错误:对象引用未设置为对象的实例。
代码
private void frmpaymentsearch_Load(object sender, EventArgs e)
{
txtcomvalue.Text = "PaymentVoucherCode";
dllby.DisplayMember = "Text";
dllby.ValueMember = "Value";
dllby.Items.Add(new { Text = "P.Voucher Code", Value = "PaymentVoucherCode" });
dllby.Items.Add(new { Text = "Vendor", Value = "VendorName" });
dllby.SelectedIndex = 0;
}
private void dllby_SelectedIndexChanged(object sender, EventArgs e)
{
txtcomvalue.Text = dllby.SelectedValue.ToString();
}
答案 0 :(得分:2)
ComboBox SelectedItem vs SelectedValue
private void dllby_SelectedIndexChanged(object sender, EventArgs e)
{
Type myType = dllby.SelectedItem.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
if(prop.Name=="value")
textBox1.Text = prop.GetValue(dllby.SelectedItem, null).ToString();
}
}
答案 1 :(得分:0)
Dictionary comboSource = new Dictionary();
comboSource.Add("1", "Sunday");
comboSource.Add("2", "Monday");
comboSource.Add("3", "Tuesday");
comboSource.Add("4", "Wednesday");
comboSource.Add("5", "Thursday");
comboSource.Add("6", "Friday");
comboSource.Add("7", "Saturday");
comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
答案 2 :(得分:0)
private void frmpaymentsearch_Load(object sender, EventArgs e)
{
txtcomvalue.Text = "PaymentVoucherCode";
dllby.DisplayMember = "Text";
dllby.ValueMember = "Value";
dllby.Items.Add(new { Text = "P.Voucher Code", Value = "PaymentVoucherCode" });
dllby.Items.Add(new { Text = "Vendor", Value = "VendorName" });
dllby.SelectedIndexChanged -= dllby_SelectedIndexChanged; // unsubscribe you event
dllby.SelectedIndex = 0;
dllby.SelectedIndexChanged += dllby_SelectedIndexChanged; // subscribe you event
}
private void dllby_SelectedIndexChanged(object sender, EventArgs e)
{
txtcomvalue.Text = dllby.Text.ToString(); // change selectedvalue to Text
}
答案 3 :(得分:0)
private void frmpaymentsearch_Load(object sender, EventArgs e)
{
txtcomvalue.Text = "PaymentVoucherCode";
dllby.DisplayMember = "Text";
dllby.ValueMember = "Value";
dllby.Items.Add(new ComboboxItem(){ Text = "P.Voucher Code", Value = "PaymentVoucherCode" });
dllby.Items.Add(new ComboboxItem(){ Text = "Vendor", Value = "VendorName" });
dllby.SelectedIndex = 0;
}
private void dllby_SelectedIndexChanged(object sender, EventArgs e)
{
txtcomvalue.Text = (dllby.SelectedItem as ComboboxItem).Value.ToString();
}
public class ComboboxItem
{
public string Text { get; set; }
public string Value { get; set; }
public override string ToString()
{
return Text;
}
}