ComboBox.SelectedValue is not Working - c#

I have a WinForms application. I've populated my ComboBox with the following code:
cboGridSize.Items.Clear();
for (int i = 2; i <= 12; i++)
cboGridSize.Items.Add(new KeyValuePair<string,int>(i.ToString(), i));
cboGridSize.SelectedValue = 4;
However, the last line has absolutely no effect. The ComboBox appears with no items selected.
So I was doing some debugging and noticed some odd things. The following image is from the watch window after setting cboGridSize.SelectedIndex to 0.
Watch Window http://www.softcircuits.com/Client/debugwin.jpg
Even though the SelectedItem property contains exactly what I would expect, SelectedValue is still null. Although the documentation for SelectedValue is pathetic, I understood it would contain the value of the selected item (SelectedItem). Instead, the two properties seem completely unrelated. Can anyone see what I have wrong?
As you can see, I have the ValueMember property set. And the DropDownStyle property is set to DropDownList.
EDIT:
Once Nikolay Khil set me straight on the issue here (why the docs for SelectedValue don't do that escapes me), I decided to simply write my own code to accomplish the same task. I'm posting it here in case anyone is interested.
static class ComboBoxHelper
{
public static void LookupAndSetValue(this ComboBox combobox, object value)
{
if (combobox.Items.Count > 0)
{
for (int i = 0; i < combobox.Items.Count; i++)
{
object item = combobox.Items[i];
object thisValue = item.GetType().GetProperty(combobox.ValueMember).GetValue(item);
if (thisValue != null && thisValue.Equals(value))
{
combobox.SelectedIndex = i;
return;
}
}
// Select first item if requested item was not found
combobox.SelectedIndex = 0;
}
}
}
This is implemented as an extension method so I simply change my original code as follows:
cboGridSize.Items.Clear();
for (int i = 2; i <= 12; i++)
cboGridSize.Items.Add(new KeyValuePair<string,int>(i.ToString(), i));
cboGridSize.LookupAndSetValue(4);

Both ValueMember and DisplayMember properties are used only if DataSource property is defined.
So, you should re-write your code as follows:
private readonly BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
public YourForm()
{
InitializeComponent();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string,int>(i.ToString(), i));
cboGridSize.SelectedValue = 4;
}
Links:
BindingList class
ObservableCollection class
INotifyCollectionChanged Interface

This does not answer the OP however...the ComboBox SelectedValue must be an integer type.
If you have a short or byte var that holds the value that will set the SelectedValue, it won't work - you will have null/nothing value.
Use an integer.

I know this is an old question but I've just come across this problem myself. I solved with the following - it's slightly hacky but it works:
if(newVal != null)
{
MyComboBox.SelectedValue = newVal;
}
else
{
MyComboBox.SelectedIndex = 0; // the 'None Selected' item
}
Hope this helps someone.

u can set SelectedValue first, and then set Datasource and others

Related

Finding a cell in devexpress datagrid

I'm new to DevExpress GridControl.
I need to find a particular cell in the grid and then do something with it's value.
How do I go about this please?
In the grid's Loaded method, I tried using myGrid.FindRowByValue("ProductType","ABC"), but always gives a negative number.
Thanks.
Here is code you can try
for (int i = 0; i < gridView1.DataRowCount; i++) {
object b = gridView1.GetRowCellValue(i, "FieldName");
if (b != null && b.Equals(<someValue>)){
gridView1.FocusedRowHandle = i;
return;
}
}
you can go to this link for more details.
https://www.devexpress.com/Support/Center/Question/Details/Q132599/get-row-by-cell-value
Unlike XtraGrid, the DXGrid for WPF does not provide the DataRowCount property - that is why we suggested checking the GridControl's ItemsSource. On the other hand, our grid has the VisibleRowCount property, which will be useful in some scenarios.
To accomplish this task, iterate through visible grid rows manually as shown below.
void MoveFocusToLast(GridControl grid, string fieldName, object value) {
for (int i = grid.VisibleRowCount - 1; i >= 0; i--) {
var handle = grid.GetRowHandleByVisibleIndex(i);
var currentValue = grid.GetCellValue(handle, fieldName);
if (currentValue != null && currentValue.Equals(value)) {
grid.View.FocusedRowHandle = handle;
return;
}
}
}
Grid also provides the FindRowByValue method, which allows you to
find a row by a specific cell value. This method returns the handle of
the corresponding row, and you can make that row visible by setting
the FocusedRowHandle property or calling ScrollIntoView. I
have prepared a sample demonstrating this approach.
See Also:
Traversing Rows
Find Row
Get RowHandle from a cell value

Find Multiple Selected ListView Item Indices in UWP App

I have a ListView named sandwichToppings which displays various sandwich toppings and allows the user to select multiple. In my controller code, I must capture the selected toppings by their index in the ListView, and send those indices back using an array.
The code which causes me to stumble is visible below. I have not been able to figure out the part which captures one or more toppings to the sandwich (the rest works fine).
void readSandwichSelection()
{
int[] toppings = null;
// One or many toppings were added to the sandwich.
if(toppingsAvailable.SelectedItems.Count > 0)
{
toppings = new int[toppingsAvailable.SelectedItems.Count];
int toppingIndex = 0;
for(int i = 0; i < toppingsAvailable.Items.Count; i++)
{
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
if(test.IsSelected == true)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}
}
// No sandwich topping.
else
{
order.addSandwich(sandwichesAvailable.SelectedIndex + 1);
}
}
Along my journey, I have tried a couple solutions found on Telerik. The first:
foreach (ListViewDataItem item in radListView1.SelectedItems)
{
int example = radListView1.Items.IndexOf(item);
}
The above example fails to work because
ListViewDataItem does not exist.
When replaced by ListViewItem, a run-time error occurs: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'Windows.UI.Xaml.Controls.ListViewItem'.'
The second attempted solution:
for (int i = 0; i < radListView1.Items.Count; i++)
{
if (this.radListView1.Items[i].Selected)
{
int example = i;
}
}
This solution cannot work because the .Selected property simply does not exist.
In all my hour of attempted work, I come up with either of these two problems. Either some form of cast exception occurs, or it is impossible to reach the property.
In my example above, I did have success in reaching the isSelected property by making a copy of each list item, and testing whether it had been selected. However, although Visual Studio lets me make the assignment
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
this statement cannot run at compile time, causing an error as written previously. Which datatype other than ListViewItem must be used to count over list view items?
toppingsAvailable.SelectedItems will return a List<> of selected items. However, how could I know from this list which list index selected items belong to?
You can try the following code to get the selected toppings's indexes and put the indexes in an array. The indexes will be saved in the ToppingArray.
void readSandwichSelection()
{
int[] ToppingArray = new int[toppingsAvailable.SelectedItems.Count];
for (int i = 0; i < toppingsAvailable.SelectedItems.Count; i++)
{
var selectedIndex = toppingsAvailable.Items.IndexOf(toppingsAvailable.SelectedItems[i]);
ToppingArray[i] = selectedIndex;
}
}
Please try the following. It is Selected rather than IsSelected.
for (int i = 0; i < toppingsAvailable.Items.Count; i++)
{
var test = toppingsAvailable.Items[i];
if (test.Selected)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}

How to set Selectedvalue in Combobox c#

I have one combobox in which I have set DataSource Value, but when I try to set SelectedValue, the ComboBox returns null. so please help.
BindingList<KeyValuePair<string, int>> m_items =
new BindingList<KeyValuePair<string, int>>();
for (int i = 2; i <= 12; i++)
m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;
cboGridSize.SelectedValue = 4;
when I set SelectedValue with 4 then it returns NULL.
Agree with #Laazo change to string.
cboGridSize.SelectedValue = "4";
or somthing similar to this
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
and refer to this looks as if it would be good for your issue:
https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem(v=vs.110).aspx
How do I set the selected item in a comboBox to match my string using C#?
Getting selected value of a combobox
I came across this question while also trying to solve this problem. I solved it by creating the following extension method.
public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
{
// In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
// that there will be an ID for the comparison.
/* Enumerating over the combo box items is the only way to set the selected item.
* We loop over the items until we find the item that matches. If we find a match,
* we use the matched item's index to select the same item from the combo box.*/
foreach (T item in cb.Items)
{
if (item.ID == id)
{
cb.SelectedIndex = cb.Items.IndexOf(item);
}
}
}
I also created an interface called IDatabaseTableClass (probably not the best name). This interface has one property, int ID { get; set; } To ensure that we actually have an ID to compare to the int id from the parameter.

How i can get the value of cell in datagrid in wpf?

I have a datagrid, with a number of rows. I want to get the value of cell[0].
In the window form I was using this code:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value == null)
{
//do somthing
}
}
The problem is, I do not know how to get the value of the cell, as this code does not work in WPF.
Like I mentioned in the comments, you need to read more on WPF and bindings that how it works because value which you are trying to get from UI can easily be fetched from underlying data object.
Say you have binded dataGrid to some list ObservableCollection<MyObject> and first column of dataGrid is binded to property Name. You can get value for first cell simply like this:
for (int i = 0; i < dataGridView1.Items.Count; i++)
{
string value = ((MyObject)dataGridView1.Items[0]).Name;
if (String.IsNullOrEmpty(textBlock.Text))
{
// do something.
}
}
That being said, assuming first cell is simple DataGridTextColumn, you can get the value in traditional WinForms way in WPF like this:
for (int i = 0; i < dataGridView1.Items.Count; i++)
{
TextBlock textBlock = dataGridView1.Columns[0]
.GetCellContent(dataGridView1.Items[i]) as TextBlock;
if (textBlock != null)
{
if (String.IsNullOrEmpty(textBlock.Text))
{
// do something.
}
}
}
== is a comparison operator. = is used for assignment:
comboBox3.Text = dataGridView1.Rows[i].Cells[0].Value.ToString();

How do I set the selected item in a comboBox to match my string using C#?

I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?
I was thinking of the line below, but this doesn't work.
comboBox1.SelectedText = "test1";
This should do the trick:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
Have you tried the Text property? It works for me.
ComboBox1.Text = "test1";
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
Assuming that your combobox isn't databound you would need to find the object's index in the "items" collection on your form and then set the "selectedindex" property to the appropriate index.
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
Keep in mind that the IndexOf function may throw an argumentexception if the item isn't found.
If the items in your ComboBox are strings, you can try:
comboBox1.SelectedItem = "test1";
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String");
Try this in windows Form.
For me this worked only:
foreach (ComboBoxItem cbi in someComboBox.Items)
{
if (cbi.Content as String == "sometextIntheComboBox")
{
someComboBox.SelectedItem = cbi;
break;
}
}
MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:
foreach (Debitor d in debitorCombo.Items)
{
if (d.Name == "Chuck Norris")
{
debitorCombo.SelectedItem = d;
break;
}
}
SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Use:
comboBox1.SelectedItem = "test1";
or:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
I've used an extension method:
public static void SelectItemByValue(this ComboBox cbo, string value)
{
for(int i=0; i < cbo.Items.Count; i++)
{
var prop = cbo.Items[i].GetType().GetProperty(cbo.ValueMember);
if (prop!=null && prop.GetValue(cbo.Items[i], null).ToString() == value)
{
cbo.SelectedIndex = i;
break;
}
}
}
Then just consume the method:
ddl.SelectItemByValue(value);
comboBox1.SelectedItem.Text = "test1";
I've filled my ComboBox with een DataTable filled from a database. Then I've set the DisplayMember and the ValueMember. And I use this code to set the selected item.
foreach (DataRowView Row in ComboBox1.Items)
{
if (Row["ColumnName"].ToString() == "Value") ComboBox1.SelectedItem = Row;
}
Supposing test1, test2, test3 belong to comboBox1 collection following statement will work.
comboBox1.SelectedIndex = 0;
This solution is based on MSDN with some modifications I made.
It finds exact or PART of string and sets it.
private int lastMatch = 0;
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
// Set our intial index variable to -1.
int x = 0;
string match = textBoxSearch.Text;
// If the search string is empty set to begining of textBox
if (textBoxSearch.Text.Length != 0)
{
bool found = true;
while (found)
{
if (comboBoxSelect.Items.Count == x)
{
comboBoxSelect.SelectedIndex = lastMatch;
found = false;
}
else
{
comboBoxSelect.SelectedIndex = x;
match = comboBoxSelect.SelectedValue.ToString();
if (match.Contains(textBoxSearch.Text))
{
lastMatch = x;
found = false;
}
x++;
}
}
}
else
comboBoxSelect.SelectedIndex = 0;
}
I hope I helped!
You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.
If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.
hope it helps.
_cmbTemplates.SelectedText = "test1"
or maybe
_cmbTemplates.SelectedItem= _cmbTemplates.Items.Equals("test1");
Enumerate ListItems in combobox
Get equal ones listindex set combobox
Set listindex to the found one.
But if I see such a code as a code reviewer, I would recommend to reconsider all the method algorithm.
I used KeyValuePair for ComboBox data bind and I wanted to find item by value so this worked in my case:
comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");
Find mySecondObject (of type MyObject) in combobox (containing a list of MyObjects) and select the item:
foreach (MyObject item in comboBox.Items)
{
if (item.NameOrID == mySecondObject.NameOrID)
{
comboBox.SelectedItem = item;
break;
}
}
ListItem li = DropDownList.Items.FindByValue("13001");
DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);
For your case you can use
DropDownList.Items.FindByText("Text");
combo.Items.FindByValue("1").Selected = true;
All methods, tricks, and lines of code setting ComboBox item will not work until the ComboBox has a parent.
I have created a Function which will return the Index of the Value
public static int SelectByValue(ComboBox comboBox, string value)
{
int i = 0;
for (i = 0; i <= comboBox.Items.Count - 1; i++)
{
DataRowView cb;
cb = (DataRowView)comboBox.Items[i];
if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
{
return i;
}
}
return -1;
}
this works for me.....
comboBox.DataSource.To<DataTable>().Select(" valueMember = '" + valueToBeSelected + "'")[0]["DislplayMember"];
I know this isn't what the OP asked but could it be that they don't know? There are already several answers here so even though this is lengthy I thought it could be useful to the community.
Using an enum to fill a combo box allows for easy use of the SelectedItem method to programmatically select items in the combobox as well as loading and reading from the combobox.
public enum Tests
{
Test1,
Test2,
Test3,
None
}
// Fill up combobox with all the items in the Tests enum
foreach (var test in Enum.GetNames(typeof(Tests)))
{
cmbTests.Items.Add(test);
}
// Select combobox item programmatically
cmbTests.SelectedItem = Tests.None.ToString();
If you double click the combo box you can handle the selected index changed event:
private void cmbTests_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Enum.TryParse(cmbTests.Text, out Tests theTest))
{
MessageBox.Show($"Unable to convert {cmbTests.Text} to a valid member of the Tests enum");
return;
}
switch (theTest)
{
case Tests.Test1:
MessageBox.Show("Running Test 1");
break;
case Tests.Test2:
MessageBox.Show("Running Test 2");
break;
case Tests.Test3:
MessageBox.Show("Running Test 3");
break;
case Tests.None:
// Do nothing
break;
default:
MessageBox.Show($"No support for test {theTest}. Please add");
return;
}
}
You can then run tests from a button click handler event:
private void btnRunTest1_Click(object sender, EventArgs e)
{
cmbTests.SelectedItem = Tests.Test1.ToString();
}
if you are binding Datasource via Dataset, then you should use "SelectedValue"
cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
You can say comboBox1.Text = comboBox1.Items[0].ToString();
Please try this way, it works for me:
Combobox1.items[Combobox1.selectedIndex] = "replaced text";
It should work
Yourcomboboxname.setselecteditem("yourstring");
And if you want to set database string use this
Comboboxname.setselecteditem(ps.get string("databasestring"));

Categories

Resources