Link to home
Start Free TrialLog in
Avatar of Eduardo Fuerte
Eduardo FuerteFlag for Brazil

asked on

Is it possible to assign programatically the combobox valuemember - item by item ?

Hi Experts!

Is it possible to assign programatically the valuemember - item by item on a combobox the valuemember ?

The reason is the first line must be empty.

     this.comboBox5.Items.Insert(0, "             ");

            for (int i = 1; i <= MyDT.Rows.Count; i++)
            {
                this.comboBox5.Items.Add(MyDT.Rows[i]["DESCRICAO"].ToString());

               // Item valuemember - just to ilustrate, this code doesn't run
                this.comboBox5.ValueMember = MyDT.Rows[i]["SB_PGE"].ToString();

            }

Open in new window


Thanks in advance!
SOLUTION
Avatar of dustock
dustock
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Assuming you're talking web:
     this.comboBox5.Items.Insert(0, "             ");

            for (int i = 1; i <= MyDT.Rows.Count; i++)
            {
                this.comboBox5.Items.Add(New ListItem(MyDT.Rows[i]["SB_PGE"].ToString(), MyDT.Rows[i]["DESCRICAO"].ToString()));
            }

Open in new window

Avatar of Eduardo Fuerte

ASKER

Hello

@dustock
Your solution doesn't work.... the first line is simply ignored when the combobox is filled.

@Angelplay
I'm using WebForms... any workaround to ListItem?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ListItem should work fine in WebForms.

You need to ensure System.Web.UI.WebControls is in scope i.e. either
using System.Web.UI.WebControls;

Open in new window

or
New System.Web.UI.WebControls.ListItem(text, value)

Open in new window

@dustock
The code
            DataRow dtRow = MyDT.NewRow();
            dtRow["SB_PGE"] = 0;
            dtRow["DESCRICAO"] = "";
            MyDT.Rows.InsertAt(dtRow, 0);
            
            comboBox5.DataSource = MyDT;
            comboBox5.ValueMember = "SB_PGE";
            comboBox5.DisplayMember = "DESCRICAO"; 

Open in new window


Works!

@AngelPlay
I referenced:
using System.Web;

ListItem still unavailable
What is the correct .net reference for it?
Well, glad I was able to help now :)
If dustock's method is working it's a cleaner solution.

System.Web.UI.WebControls (see above). Maybe at somepoint in the future if you have something more dynamic you might need to manually add listitems.
Pretty good solution!

Now my combobox is much more configurable than before.

Thanks for all!