c# - Set ComboBox Text on Basis of SelectedIndex -
i trying set text
property of combobox on basis of selectedindex problem text
becoming string.empty
after changing index of combobox.
each item in combobox correspond string in datatable
having 2 columns name
, description
what need when users select's name (index changes) when want show description of in combobox
what have tried :
private void tbtag_selectionchangecommitted(object sender, eventargs e) { // data selected index tagrecord tag = tbtag.selecteditem tagrecord; // after getting data reset index tbtag.selectedindex = -1; // after resetting index, change text tbtag.text = tag.tagdata; }
how have populated combobox
//load tag list datatable tags = tagmanager.tags; foreach (datarow row in tags.rows) { tagrecord tag = new tagrecord((string)row["name"], (string)row["tag"]); tbtag.items.add(tag); }
helper class used :
private class tagrecord { public tagrecord(string tagname, string tagdata) { this.tagname = tagname; this.tagdata = tagdata; } public string tagname { get; set; } public string tagdata { get; set; } public override string tostring() { return tagname; } }
i think happens because -1 index in combobox
means no item selected (msdn) , trying change text of it. create 1 more element (at index 0) , make change text depending on selection:
bool newtagcreated = false; private void tbtag_selectionchangecommitted(object sender, eventargs e) { tagrecord tag = tbtag.selecteditem tagrecord; tagrecord newtag = null; if (!newtagcreated) { newtag = new tagrecord(tag.tagdata, tag.tagname); //here change going displayed tbtag.items.insert(0, newtag); newtagcreated = true; } else { newtag = tbtag.items[0] tagrecord; newtag.tagname = tag.tagdata; } tbtag.selectedindex = 0; }
Comments
Post a Comment