1
votes

I am trying to set the Text property of ComboBox on the basis of SelectedIndex but the problem is Text is becoming String.Empty after changing the Index of Combobox.

Each Item in ComboBox correspond to a string in DataTable having 2 columns Name, Description

What i need is when users select's a Name (Index Changes) when i want to show the Description of that in ComboBox

What i have tried :

private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{
    // get the data for the selected index
    TagRecord tag = tbTag.SelectedItem as TagRecord;

    // after getting the data reset the index
    tbTag.SelectedIndex = -1;

    // after resetting the index, change the text
    tbTag.Text = tag.TagData;
}

How i have populated the Combobox

//load the 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;
    }
}
2

2 Answers

0
votes

I think that happens because -1 index in ComboBox means that no item was selected (msdn) and you are trying to change text of it. I would create one more element (at index 0) and make it change text depending on selection:

bool newTagCreated = false;

private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{

    TagRecord tag = tbTag.SelectedItem as TagRecord;
    TagRecord newtag = null;

    if (!newTagCreated)
    {
      newtag = new TagRecord(tag.TagData, tag.TagName); //here we change what is going to be displayed

      tbTag.Items.Insert(0, newtag);
      newTagCreated = true;
    }
    else
    {
      newtag = tbTag.Items[0] as TagRecord;
      newtag.TagName = tag.TagData;
    }

    tbTag.SelectedIndex = 0;
}
0
votes

Found a solution.

private void tbTag_SelectedIndexChanged(object sender, EventArgs e)
{
    TagRecord tag = tbTag.SelectedItem as TagRecord;
    BeginInvoke(new Action(() => tbTag.Text = tag.TagData));
}