[Gtk-sharp-list] Example of using ComboBox

Ben Motmans Ben Motmans <ben.motmans@gmail.com>
Tue, 19 Apr 2005 23:26:35 +0200


On 4/19/05, xiii29 <xiii29@free.fr> wrote:
> Hi,
>=20
> I'm wondering if someone can send me an example of using the
> Gtk.ComboBox with AddAttributes ...
>=20
> I'have a collection of object with Id and Name property. My goal is to
> be able to show the name but get the id ...
>=20
> I can't find any help doc ...
>=20
> Thanks for any help !
>=20

You can store anything you want in a ListStore, and you don't need to
show all columns you add in the ListStore

for example:

using System;
using Gtk;

public class ComboBoxDemo : Window {

=09private ListStore store;

=09public ComboBoxDemo () : base ("ComboBoxDemo") {
=09=09this.SetSizeRequest(420, 360);

=09=09this.WindowPosition =3D WindowPosition.Center;
=09=09this.DeleteEvent +=3D new DeleteEventHandler (WindowClose);

=09=09VBox vbox =3D new VBox (false, 5);
=09=09vbox.BorderWidth =3D 10;


=09=09CellRendererPixbuf pixbuf =3D new CellRendererPixbuf ();
=09=09CellRendererText text =3D new CellRendererText ();

=09=09store =3D new ListStore (typeof (Gdk.Pixbuf), typeof (string), typeof=
 (int));
=09=09ComboBox combo =3D new ComboBox (store);
=09=09combo.Changed +=3D new EventHandler (OnChange);

=09=09combo.PackStart (pixbuf, false);
=09=09combo.PackStart (text, false);

=09=09combo.AddAttribute (pixbuf, "pixbuf", 0);
=09=09combo.AddAttribute (text, "text", 1);

=09=09int id =3D 0;
=09=09string[] stockIds =3D Gtk.Stock.ListIds();

=09=09foreach (string stockItemName in stockIds) {

=09=09=09Gdk.Pixbuf image =3D this.RenderIcon (stockItemName,
IconSize.SmallToolbar, "");

=09=09=09store.AppendValues (image, stockItemName, id);
=09=09=09id++;

=09=09}
=09=09TreeIter iter;
=09=09if (store.GetIterFirst (out iter))
=09=09=09combo.SetActiveIter (iter);

=09=09vbox.PackStart (combo, false, false, 0);

=09=09this.Add (vbox);

=09=09this.ShowAll ();
=09}

=09private void WindowClose (object o, DeleteEventArgs args)
=09{
=09=09this.Destroy ();
=09=09Application.Quit ();
=09}

=09private void OnChange (object o, EventArgs args)
=09{
=09=09TreeIter iter;
=09=09if ((o as ComboBox).GetActiveIter (out iter)) {
=09=09=09string text =3D (string)store.GetValue (iter, 1);
=09=09=09int id =3D (int)store.GetValue (iter, 2);
=09=09=09Console.WriteLine (text + " (id=3D" + id + ")");
=09=09}
=09}

=09public static void Main (string[] args)
=09{
=09=09Application.Init ();
=09=09new ComboBoxDemo ();
=09=09Application.Run ();
=09}
}

(compile with:  mcs -pkg:gtk-sharp-2.0 ComboBoxDemo.cs)

It will show an image and some text, but when you change the
selection, the text and the ID is written to the console

-- Ben