Ayman Ayman - 5 days ago 6
C# Question

Changing value of textbox according to the selected combobox value

I have tried the below code to get selected value of combo-box to textbox but it give me the following error

Error : Object reference not set to an instance of an object.

Code

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

Answer

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