joncodo
joncodo

Reputation: 2328

Bind a property to a custom control

I have a custom control library that I am using and I have added a property called DataCodeField that acts nearly the same as DataTextField for a control that inherits from ComboBox.

    DummyData data1 = new DummyData(12, "Jon", 1);
    DummyData data2 = new DummyData(15, "Bill", 2);
    DummyData data3 = new DummyData(23, "Ted", 1);

    var people = new List<DummyData>{data1, data2, data3};

    ddlTest.DataSource = people;
    ddlTest.DataTextField = "Name";
    ddlTest.DataCodeField = "Age";
    ddlTest.DataValueField = "Id";
    ddlTest.DataBind();

    var id = ddlTest.SelectedValue;
    var index = ddlTest.SelectedIndex;
    var name = ddlTest.SelectedItem;
    var age = ??

I need to find the persons age when I bound it to the new DataCodeField. I know I have to override the OnDataBinding event to do this but I can't seem to find where to start. Any help would be appreciated. My end goal is to access the age like this after the combobox has been databound.

Alternatively, is there a way to access the bound datasource and then access the age from that object based on the selectedIndex?

Upvotes: 0

Views: 92

Answers (1)

Magnus
Magnus

Reputation: 46929

If you save the datasource in viewstate you can access the selected age using;

var age = People[ddlTest.SelectedIndex].Age;

Upvotes: 1

Related Questions