C# Set combo item with selectedValue - c#

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.

Related

How to add an item to ComboBoxEdit?

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!

How to select an Item from asp:Dropdownlist on Page load from Code Behind C#?

I tried so many articles around, like below to get my task done, but didn't work as I always ends up with an NullReferenceException, I have bound a database table column to the Dropdown list, on page load i want to select an item based on the value from database which is one of those listed items. Please help me.
txt_examtype.DataSource = dt;//txt_examtype is the dropdownlist
txt_examtype.DataTextField = "ExamTypeName";
txt_examtype.DataValueField = "ExamTypeName";
txt_examtype.DataBind();
String examtype = dt.Rows[0]["ExamType"].ToString().Trim();
ListItem myitem = txt_examtype.Items.FindByValue(examtype);
txt_examtype.SelectedValue = myitem.Value;
try this code
txt_examtype.SelectedValue = dt.Rows[0]["ExamType"].ToString()
You should set SelectedIndex instead of SelectedValue. This is safe to use:
txt_examtype.SelectedIndex = txt_examtype.Items.IndexOf(txt_examtype.Items.FindByValue(examtype));

Set SelectedValue in DataGridViewComboBoxColumn or DataGridViewComboBoxCell

I would like to set a value to the ComboBox in the DataGridView. I already have changed the comboBoxItems, I just want to select one of them. Thank you in advance!!!
I already solved my problem... I'm gonna post the way I did and hoppefully someone will find this answer too.
dgrDetalle.DataSource = dataTable("select * from yourTable");
DataTable dtCombo = dataTableCombo("select COL_ID DETOC_COL_FK,COL_DESCRIPCION from yourTable2");
string[] strColumns = new string[] { "COL_DESCRIPCION" };
MultiColumnDictionary map = new MultiColumnDictionary(dtCombo, "DETOC_COL_FK", strColumns, 0);
dgrDetalle.Cols["DETOC_COL_FK"].DataMap = map;
As you can see the class that save my life is MultiColumnDictionary.
Note: The combobox items must be loaded in a different DatatTable than the DataTable that is gonna load directly in the grid.
As far as I know, the Comboboxes only actually exist as controls when they are being edited, and therefore don't have a selected item property.
You can simply set the Value property of the cell to the item you want selected, or alternitively, you can set a default value by setting the property:
DataGridViewColumn.DefaultCellStyle.NullValue.

FormatException on a DataGridViewComboboxCell.Value

I have a problem which I can't figure out.
I have an DataGridViewComboboxCell,
List<ComboBoxItem> klanten = new List<ComboBoxItem>();
foreach (ICustomer customer in CustomerFactory.CreateCustomers())
{
klanten.Add(new ComboBoxItem(customer.Naam, customer.Id));
}
klanten.Add(new ComboBoxItem("Klant aanvraag", -1));
uxInvoerenKlant.DataSource = klanten;
uxInvoerenKlant.DisplayMember = "Text";
uxInvoerenKlant.ValueMember = "Value";
When the option "Klant aanvraag" is selected the user gets a window where the user can choose another customer.
This is for the reason the user was not assigned for a specific project for that customer.
When the user chose one it will be changed in the Combobox with the following code.
uxUrenInvoeren[collumnIndex, row.Index].Value = uxInvoerenKlant.Items[klantIndex];
klantindex is the customer that needs to be selected, because it is retrieved from the combobox. It is the right kind of object in my opinion.
After this, the datagridview_dataerror event is raised where I get the Format exception with the following exception text.
DataGridViewComboBoxCell value is not valid.
What is the problem?
I found the problem myself.
The uxUrenInvoeren[collumnIndex, row.Index].Value contained the value of the ComboBoxItem and not the ComboBoxItem itself. The code now looks like this:
ComboBoxItem item = uxInvoerenKlant.Items[klantIndex] as ComboBoxItem;
if (item != null)
{
uxUrenInvoeren[collumnIndex, row.Index].Value = item.Value;
}
In this way it goes well.
Thanks for the help!
I think it may be your value of -1. Maybe you need to start with 0
You should add the selected value to the items collection of the combobox, the exception is raised since the value assigned is not found in the Item collection of the ComboBoxColumn and hence not a valid value.
Try adding it using Add
(dataGridView1.Columns[0] as DataGridViewComboBoxColumn).Items.Add
Solution :
Private Sub gvPrint_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles gvPrint.DataError
If e.Context = DataGridViewDataErrorContexts.Formatting Or e.Context = DataGridViewDataErrorContexts.PreferredSize Then
e.ThrowException = False
End If
End Sub

Setting dropdownlist selecteditem programmatically

I want to set the selecteditem attribute for an ASP.Net dropdownlist control programmatically.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
Assuming the list is already data bound you can simply set the SelectedValue property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue variable would need to exist in the property specified within the DataValueField in your controls databinding.
UPDATE:
If the value of myValue doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.
Here is the code I was looking for :
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByText("PassedValue"));
Or
DDL.SelectedIndex = DDL.Items.IndexOf(DDL.Items.FindByValue("PassedValue"));
Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:
dropdownlist1.Text="Your Value";
This will work only if the value is existing in the data-source of the dropdownlist.
If you need to select your list item based on an expression:
foreach (ListItem listItem in list.Items)
{
listItem.Selected = listItem.Value.Contains("some value");
}
Just Use this oneliner:
divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;
where divisions is a dropdownlist control.
Hope it helps someone.
var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);
OR
foreach (var listItem in ctx.Items)
listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);
Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
On load of My Windows Form the comboBox will display the ClassName column of my DataTable as it's the DisplayMember also has its ValueMember (not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
ddlemployee.DataSource = ds.Tables[0];
ddlemployee.DataTextField = "Employee Name";
ddlemployee.DataValueField = "RecId";
ddlemployee.DataBind();
ddlemployee.Items.Insert(0, "All");

Categories

Resources