Ronaldo Nascimento Ronaldo Nascimento - 6 months ago 27
C# Question

How to set the value of a Gtk.ComboBox?

All I can figure out is something to do with the ComboBox.GetEnumerator or something like that.

I would like to do something like:

System.Collections.IEnumerator e = this.task_difficulty_combobox.GetEnumerator();
while (e.MoveNext())
if (e.ToString() == this.task.Difficulty.ToString())
Gtk.TreeIter i = (Gtk.TreeIter)e.Current;

However, This doesn't work.

kdt kdt

The reason your code doesn't work is that the "items in the combobox" are actually the cell renderers packed into it for displaying columns of data. To get at the actual data, you need the TreeModel object.

If you really must select based only on what's in the combo, here's how you can do it:

string[] values = new string[]{"one", "two", "three"};
var combo = new ComboBox(values);

Gtk.TreeIter iter;
combo.Model.GetIterFirst (out iter);
do {
  GLib.Value thisRow = new GLib.Value ();
  combo.Model.GetValue (iter, 0, ref thisRow);
  if ((thisRow.Val as string).Equals("two")) {
    combo.SetActiveIter (iter);
} while (combo.Model.IterNext (ref iter));

However, generally it's more succinct to keep your values indexed, like this:

List<string> values = new List<string>(){"one", "two", "three"};  
var combo = new ComboBox(values.ToArray());

// Select "two"
int row = values.IndexOf("two");
Gtk.TreeIter iter;
combo.Model.IterNthChild (out iter, row);
combo.SetActiveIter (iter);