How to add an item to ComboBoxEdit? - c#

I have a small problem with ComboBoxEdit (DevExpress.XtraEditors). I cannot add a value or set SelectedIndex for my ComboBoxExit.
ComboBoxEdit combo = new ComboBoxEdit();
ComboBoxItemCollection coll = combo.Properties.Items;
coll.BeginUpdate();
try
{
coll.Add(new PersonInfo("Sven", "Petersen"));
coll.Add(new PersonInfo("Cheryl", "Saylor"));
coll.Add(new PersonInfo("Dirk", "Luchte"));
}
finally
{
coll.EndUpdate();
}
combo.SelectedIndex = -1; Comboboxedit1.Properties.Items.Add(combo);
It does not work and just adds shows this:

WIth this line :
Comboboxedit1.Properties.Items.Add(combo);
You are adding the ComboBox object inside itself. ComboBoxEdit ToString() method returns the name you are seeing in your screenshot.
So, remove this line.
Your code in taken from the official DevExpress documentation (except the line above that you should remove), and works fine : items are indeed added.
However, setting the SelectedIndex property to -1 doesn't select anything, as the documentation states :
The BaseListBoxControl.SelectedIndex property is set to -1 for
demonstrative purposes (the property is set to -1 by default). This
ensures that no item is currently selected in the combo box.
You can do :
combo.SelectedIndex = 0; // Select Sven
Or
combo.SelectedIndex = 1; // Select Cheryl
Or
combo.SelectedIndex = 2; // Select Dirk

Use some like this:
try
{
ComboBoxEdit combo = new ComboBoxEdit();
combo.Properties.Items.Add("Sven, Petersen");
combo.Properties.Items.Add("Cheryl, Saylor");
combo.Properties.Items.Add("Dirk, Luchte");
}
Will work fine!
No complication, no inovation, simple like need be!

Related

C# What does setting the SelectedIndex of a combobox to -1 do?

When I was working on one of my projects I was trying to write to a datasourced combobox and then write a value into the combobox like below:
//Create list for combobox
List<string> companyList= new List<string>() { "", "Company1", "Company2" };
//Datsource list to combobox
cbCompanyName.DataSource = companyList;
//If form is set to import data and the billing address is not null
if (importAddress && StaticValues.billAddress != null)
{
//Fill all fields with data from Static Values class
cbCompanyName.Text = StaticValues.billAddress.CompanyName;
cbCountry.Text = StaticValues.billAddress.Country;
}
else
{
//Set country to US
cbCountry.SelectedIndex = 0;
}
however the line cbCompanyName.Text = StaticValues.billAddress.CompanyName; ran without writing any text to the combobox, until I set the selected index of the combobox to -1. What does setting the combobox selected index to -1 do that would change this as apposed to setting the selected index to 0?
Setting the SelectedIndex on a ComboBox to -1 deselects (SelectedItem is NULL). Setting to 0 selects the first item in Items
Combobox needs to know what is my value and display member,
giving the datasource is not enough for it.
I think you can use like this or
// comboBox.DisplayMember = "Text";
// comboBox.ValueMember = "Value";
int =0;
companyList.forEach(x=> comboBox.Items.Add(new { Text = x.toString(), Value =i++ }));
comboBox1.SelectedIndex = 0;
you can look this article
similar question and answers

combobox item selected To be fixed

I had a databound combobox in my windows form I populate it by a function deptload() IN FORM LOAD
public void DeptcomboLoad()
{
DataTable dt = depttrans.getDeptName();
Cmb_Department.DataSource = dt;
Cmb_Department.DisplayMember = "DepartmentName"; //CHAR
Cmb_Department.ValueMember = "DepartmentPK"; //INT
}
Now when an employee of a department (say accounts DepartmentName="Accounts " , DepartmentPK=23 ) login I want the ComboBox text to be selected as "acounts "
and when I go to get the selected value of the ComboBox I should get 23
I tried
Cmb_Department.selectedtext="Accounts"
Cmb_Department.Text="Accounts"
but its not giving the selected value
Can anyone give a suggestion
Instead of trying to put a value INTO the combobox, try to GET the SelectedItem like this:
string txt= Cmb_Department.SelectedItem.Text
or just:
string txt= Cmb_Department.SelectedText
To change selected value of the combobox you can use
SelectedItem property or SelectedIndex.
Index must be exact number in your data sourse, and Item must be exact object from datasource
You can get it to select the right item by issuing something like this:
Cmb_Department.SelectedValue = 23;
Where 23 comes from some other variable, maybe on another object, maybe from a local variable, whatever works in your case.
Now, to get the selected value you can use this statement:
var val = Cmb_Department.SelectedValue;
To get the selected text (which would be the text associated with the value):
var text = ((DataRow)Cmb_Department.SelectedItem)["DepartmentName"];
The reason I'm prescribing the aforementioned is because the SelectedText property is volatile, and the Text property doesn't always work based on how the DropDownStyle is set.
However, some would probably argue to get the same as the aforementioned you could issue this statement:
var text = Cmb_Department.Text;

Combobox Selected Index is changing to 0 when data is appended to it

Hi I am using the following code in the form load
Combobox1.DataSource=GetItems();
Then by default first item is selected.
I suppose your ComboBox has the DropDownStyle property set to DropDownList. When it is, setting the Datasource automatically sets the SelectedIndex to 0 (first element in the list). You could write:
Combobox1.DataSource=GetItems();
Combobox1.SelectedIndex = -1;
You're not appending data, you're replacing it entirely. So the SelectedIndex will be reset. You could remember it and then set it back like so
int oldIndex = Combobox1.SelectedIndex;
Combobox1.DataSource= GetItems();
Combobox1.SelectedIndex = oldIndex; //should check to see if the new list is long enough.

C# Set combo item with selectedValue

I am dynamically creating a combobox like this:
public Control GenerateList(Question question)
{
// Get a list with answer possibilities
List<QuestionAnswer> answers = question.GetAnswers();
// Get a collection of given answers
Collection<QuestionnaireAnswer> givenAnswers = question.GetFilledAnswers();
ComboBox cmb = new ComboBox();
cmb.Name = "cmb";
cmb.DataSource = answers;
cmb.DisplayMember = "Answer";
cmb.ValueMember = "Id";
// Check an answer is given to the question
if (givenAnswers != null && givenAnswers.Count > 0)
{
cmb.SelectedValue = givenAnswers[0].AnswerId;
}
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.SelectedIndexChanged += new EventHandler(cmb_SelectedIndexChanged);
cmb.Leave += new EventHandler(cmb_Leave);
return cmb;
}
The problem is,when executing cmb.SelectedValue = givenAnswers[0].AnswerId; cmb.SelectedValue is always null.
When debugging and I explore answers (the datasource) I see that Id (ValueMember) is exactle the same as AnswerId (in the if statement). Both have the same type (long) and the same value, but SelectedValue stays null.
Is there something I don't see?
EDIT:
It looks like the combobox stays empty. When I replace cmb.SelectedValue = givenAnswers[0].AnswerId; with cmb.SelectedIndex = 0; I get an ArgumentOutOfRangeException. This while the answers collections count is 2. So the datasource isn't null... Very strenge huh?
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
Solution:
The SelectedValue, SelectedIndex, SelectedItem properties can't be set until the control is added to the form. After the control is added to the form, the selectedValue, -Index and -Item properties can be set.
I met this weird issue before, at last I gave up and used another way:
cmb.Items.FindByValue(givenAnswers[0].AnswerId).Selected = true;
It worked fine...Hope you good luck!
cmb.SelectedIndex = cmb.FindStringExact("Desired Value")
The cmb.FindStringExact("Desired String") returns the index of the value you would like to select and the cmb.SelectedIndex sets the combobox to that index.
Thanks to Billious for showing me the light!
FYI - This is the VB.NET Winforms Version.
Are you looking at the same property?
cmb.ValueMember = "Id";
..
cmb.SelectedValue = givenAnswers[0].AnswerId;
You're refering to another ValueMember then the Id you're posting into the SelectedValue.
Besides that you might want to try to set your Display- and Value-member before databinding. It's faster.
Make sure QuestionAnswer has public accessors corresponding (same name) to the Display/Value Members you use.
I ran into the same problem, and found that my issue was I was treating SelectedValue as an integer, when in actual fact it was an object. The "FindByValue" solution from Danny Chen above doesn't work in WinForms, so I tried using "FindStringExact" and searched on the DisplayMember:
cmb.Items.FindStringExact(<Display string>)
Not an ideal solution, but it worked.

ListView DataItem Shows Null

A few days ago, I wrote about issues with implementing a ListView in ASP.NET. Now, with all of the other code written, I'm having trouble saving changed items in a ListView.
A few things of note:
The Save button is not part of the ListView proper; it calls the GetListViewItems() method, which in turns call the Save() method.
The Listview.DataBind() event is invoked when a button is pressed requesting the records to be updated
The Listview shows text using <%#Eval("Key.Name") %> and a named DropDownList using <%#Eval("Value") %>
Getting The Items From the ListView
public void GetListViewItems()
{
List<Foo> Result = FooManager.CreateFooList();
DropDownList ddl = null;
ListViewItem Item = null;
try
{
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
foo.Id = item.DataItemIndex; //shows null
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
}
}
}
catch (Exception ex)
{
//Irrelevant for our purposes
}
}
DataBinding the ListView
The code to databind the ListView is shown here in my previous question.
Question(s):
Why is it that when I iterate through the ListViewDataItem in the Listview that each item is null?
How can I retrieve the Foo.Id from the Dictionary?
What else might I be missing?
What would I use if I wanted to get that Id Programmatically based on what items were shown? As it is now, the current ListView is shown based on what Foos were selected. Those Foos selected are then displayed, and the user can change the Bar in the DropDownList, hit Save, and those changes are propogated.
Update
As it turns out, my problem was what leppie had said; and that was that I needed to specify DataKeyNames and use those to retain the information from the ListView.
Here's the code I added:
try
{
int DataKeyArrayIndex = 0;
foreach (ListViewDataItem item in lvFooList.Items)
{
Item = item;
ddl = ((DropDownList) (Item.FindControl("ddlListOfBars")));
if (//something is there)
{
Foo foo = FooManager.CreateFoo();
Foo tempFoo = FooManager.CreateFoo();
if (lvFooList != null)
{
tempFoo = ((Foo)(lvFooList.DataKeys[DataKeyArrayIndex].Value));
}
foo.Id = tempFoo.Id;
int barId = int.Parse(ddl.SelectedItem.Value); //works just fine
foo.barId = barId;
Result.Add(foo);
DataKeyArrayIndex++;
}
}
}
And then in the .ascx file, I added DataKeyNames="Key", like so:
<asp:ListView ID="lvFooList" runat="server" DataKeyNames="Key">
This allowed me to use the Key from my previous post to determine which Foo was being looked at.
Any critiques of this approach, as well as methods for making it better are greatly appreciated.
Some quick answers:
Your need to use databinding for that to work, in other words, assign to DataSource and call DataBind(). EDIT: seems you are doing that. But remember it wont persist between postbacks, just the DataKey (see below).
If I recall correctly, you need to specify the DataKeyNames, and they can be retrieved from the DataKey property then.
you can also use the ListViewDataItem.DataItemIndex property instead of keeping your own index, as in:
foreach (ListViewDataItem item in MyListView.Items)
{
// in this example key is a string value
Foo foo = new Foo(MyListView.DataKeys[item.DataItemIndex].Value as string);
// do stuff with foo
}

Categories

Resources