[Gtk-sharp-list] ComboBox with two columns

Michael Hutchinson m.j.hutchinson at gmail.com
Mon Oct 13 13:45:55 EDT 2008


On Mon, Oct 13, 2008 at 7:48 AM, Mex <meelis.lilbok at deltmar.ee> wrote:
>
> Hi all
>
> I know how to fill combobox with two columns from database.
> But how to display only one column, when first is typeof int and second
> string
> Lets say values are
> 1 - Red
> 2 - Blue
> 3 - Black
>
> displayed are only Red, Blue and Black, but when user selects Blue i get
> back 2.

Create a ListStore with an int column and a string column, and use it
as the combo's model. Pack a CellRendererText into the combo and map
its text property to the text column in the model. You can use the
GetActiveIter method to get the TreeIter of the selected row, then use
listStore.GetValue (iter, column) to get the value from the store's
int column.

//create a list store with and int columns and a string column
//and set it to be our combo's model
ListStore model = new ListStore (typeof (int), typeof (string));
combo.Model = model;

//use constants for our column indices so it's easier to get them right
const int COL_INT = 0;
const int COL_TEXT = 1;

//create a text renderer and add it to the combo box
//note that you can pack in multiple renderers, e.g. an icon renderer
CellRendererText textRenderer = new CellRendererText ();
combo.PackStart (textRenderer, true);

//map the "text" property of the renderer to column 0 in the model
//note that you can map any columns in the model to any properties of
the renderer
combo.AddAttribute (textRenderer, "text", COL_TEXT);

//add some values to the model
//note that the order of values corresponds to the columns
model.AddValues (1, "Red");
model.AddValues (2, "Blue");

//get the selected value
if (combo.GetActiveIter (out activeIter)) {
    myIntValue = model.GetValue (activeIter, COL_INT);
}



These same principles apply to the TreeView.


-- 
Michael Hutchinson
http://mjhutchinson.com


More information about the Gtk-sharp-list mailing list