C# Combobox Selected.Index = -1 not working - c#

It should reset the Combobox to no value, Combobox is in the same panel, but the code sets the index to 0 wich is the first value of the data binded list.
It works on the second click tho...ON the first click it sets the index to 0, on the second to -1.
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
}
}

Perhaps you could try adding a dummy first item to your ComboBox to act as a placeholder.
This way you can deselect simply using ComboBox.SelectedIndex = 0;
Just be sure not to interpret this item in the ComboBox as a real item anywhere.
Also, try:
ComboBox.ResetText();
ComboBox.SelectedIndex = -1;
Or:
ComboBox.SelectedItem = null;

thanks all for answers...in the end I solved the issue with a workaround. The problem was, that button of the code above needed two clicks to set index to -1.
On the first click it moved to 0 and on the second to -1. I dont know why tho...Another problem was i had a index changed event on combobox and i wanted to fire it only once - not twice.
I solved the problem this way...
if (((Button)sender).Parent.Controls.OfType<ComboBox>().Count() > 0)
{
foreach(ComboBox C in ((Button)sender).Parent.Controls.OfType<ComboBox>().ToList())
{
if(C.SelectedIndex != -1)
{
C.SelectedIndexChanged -= this.ComboBox_Promo_SelectedIndexChanged;
while (C.SelectedIndex != -1)
{
C.SelectedIndex = -1;
}
C.SelectedIndexChanged += this.ComboBox_Promo_SelectedIndexChanged;
this.ComboBox_Promo_SelectedIndexChanged(C, EventArgs.Empty);
}
}
}

Related

Pass the Selected Value in DataGridView to ComboBox

When I clicked on a cell in my DataGridView, the values are passed on my Textboxes, but I have a problem when it comes to my combobox, it just stays null. I've already tried SelectedItem and SelectedIndex but it stays null. I've manage to place the value in my combobox using SelectedText but once I've updated my database, I'm getting a NullReferenceException in my combobox, here's my code:
private void dgvStudentRecord_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dgvStudentRecord.Rows[e.RowIndex];
txtStudNum.Text = row.Cells["studentId"].Value.ToString();
txtStudName.Text = row.Cells["studentName"].Value.ToString();
cboSection.SelectedText = row.Cells["section"].Value.ToString();
numPrelim.Value = Convert.ToDecimal(row.Cells["prelim"].Value);
numMidterm.Value = Convert.ToDecimal(row.Cells["midterm"].Value);
numFinals.Value = Convert.ToDecimal(row.Cells["finals"].Value);
}
}
You're going to have some headache doing it the way you are approaching it because the ComboBox does not handle unexpected values well at all, and the SelectText property it not doing what you think its doing (its NOT selecting an item from its internal list when you set that property) (see: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedtext(v=vs.110).aspx)
You are going to be better of writing something like:
int index = cboSection.FindString(row.Cells["section"].Value.ToString());
if(index > -1)
{
cboSection.SelectedIndex = index;
}
else
{
object newSection = row.Cells["section"].Value.ToString();
cboSection.Items.Add(newSection);
cboSection.SelectedItem = newSection;
}
Edited to show conditional select or add.
Final edit... Doh.
Try this, ComboBox.Text property
combobox1.Text=row.Cells[cellIndex].Value.ToString();

WPF ListBox always previous item selected on each change of selection?

I am facing strange problem regarding WPF ListBox. I have tried all variations of setting ListBox bindings, but it still the same.
As soon as I change the selection and click on different item other than which is already selected, It jumps back to the previous selected item. On second click , it get selected afterwards which is completely wrong.
I debugged and see that everything is al right. After calling RaisePropertyChange(Property), it jumps to the getter section of property and everything fine there too. It is returning the valid value from there.
But after returning and before displaying again selected value, something bad happens and due to that, it jumps back to the previously selected item ( anchorItem ).
Following is the XAML for this.
<ListBox x:Name="yGradesListBox"
Style="{StaticResource enumListBox}"
SectedValue="{Binding Path=SelectedYieldGrade}"/>
While The binding Property is :
public YieldGrade SelectedYieldGrade
{
get
{
if (_sides[0].YieldGradeState == SelectionState.Selected)
return YieldGradeConverter.Convert(_sides[0].YieldGrade);
if (_sides[1].YieldGradeState == SelectionState.Selected)
return YieldGradeConverter.Convert(_sides[1].YieldGrade);
//this is the condition that meets after RaisePropertyChange and it has to be returned.
if (this.CarcassDto.USDAYieldGrade != YieldGrade.NoGrade)
return this.CarcassDto.USDAYieldGrade;
return YieldGrade.NoGrade;
}
set
{
if (this.CarcassDto.USDAYieldGrade == YieldGrade.NoGrade || this.CarcassDto.USDAYieldGrade != value)
{
this.CarcassDto.USDAYieldGrade = value;
foreach (SideViewModel sideData in _sides.Where(sideData => sideData.HasData))
{
sideData.YieldGradeState = SelectionState.Overwritten;
}
this.CarcassDto.YieldGradeOverrideState = this.GetYieldGradeOverride();
RaisePropertyChanged("SelectedYieldGrade");
_model.OnCarcassDataChanged(this, new CarcassDataChangedEventArgs() { RecalcProgram = true });
}
}
}
and YieldGrade type is Enum defined in the code
public enum YieldGrade
{
[Description("No Grade")]
NoGrade = 0,
[Description("Y1")]
YG1 = 1,
[Description("Y2")]
YG2 = 2,
[Description("Y3")]
YG3 = 3,
[Description("Y4")]
YG4 = 4,
[Description("Y5")]
YG5 = 5
}
Now If I click on any item represented by above enum, the selection would be jumped back to the anchor value( i.e the previously selected ).
I ahve applied all combinitions of properties in markup ( e.g TwoWay, SelectedItem )
Please help me out to solve this , I would be extremly obliged. I am kind a stuck here.
Regards
Usman
You are trying to do too much with get set
The get should return the set
If this is your set
this.CarcassDto.USDAYieldGrade = value;
Then this should be your get
return this.CarcassDto.USDAYieldGrade;
And you should not modify this.CarcassDto.USDAYieldGrade in the get
This is just squirrely
if (this.CarcassDto.USDAYieldGrade != YieldGrade.NoGrade)
return this.CarcassDto.USDAYieldGrade;
return YieldGrade.NoGrade;
Same as
if (this.CarcassDto.USDAYieldGrade == YieldGrade.NoGrade)
{
return YieldGrade.NoGrade;
}
else
{
return this.CarcassDto.USDAYieldGrade;
}
Same as
if (this.CarcassDto.USDAYieldGrade == YieldGrade.NoGrade)
{
return this.CarcassDto.USDAYieldGrade;
}
else
{
return this.CarcassDto.USDAYieldGrade;
}
Same as
return this.CarcassDto.USDAYieldGrade;

Dropdownlist.selectedItem.text in Dropdownlist not working

I am populating the value from the DB table to a dropdown Field, but when it is getting bound to the drop-down list in the screen the exact value is getting bound, but 2 times (ie. Duplicate value is getting bound) in the drop-down list along with the original Value.
if (ddlhour.Items.Contains(ddlhour.Items.FindByValue(time[0].ToString())))
{
ddlhour.SelectedItem.Text = time[0].ToString();
}
In the SelectedItem.Text the value is getting duplicated .
Can anyone help me solve the issue?
Where in time[0], there is a Text from the DB table.
FindBYText
int index = ddlhour.Items.IndexOf(ddlhour.Items.FindByText("Others"));
//index = 1
if (index != -1) {
ddlhour.SelectedIndex = index;
}
FindBy Value
int j = ddlhour.Items.IndexOf(ddlhour.Items.FindByValue("Others"));
if (j != -1) {
ddlhour.SelectedIndex = j;
}
Try this:
if (ddlhour.Items.Contains(ddlhour.Items.FindByValue(time[0].ToString())))
{
ddlhour.Items.FindByValue(time[0].ToString()).Selected = true;
}
use selectedValue
ddlhour.SelectedValue = time[0].ToString();
ddlhour.SelectedItem.Text changes the text of selected item

moving one value form list to another delete next value from list

I have two listboxes when i swap value to another listbox it always remove next value from the list and when i try to swap last value from the list it take top one value form the list . I try to find the problem but i don't get any result. Below is the code part for review.
private void MoveListBoxItems(ListBox lstEmployeelist, ListBox lstSelectedEmployees)
{
ListBox.SelectedObjectCollection sourceItems = lstEmployeelist.SelectedItems;
List<Master> newsource = this.masterBindingSource.DataSource as List<Master>;
List<Master> _selectedSource = this.masterSellectedBindingSource.DataSource as List<Master>;
try
{
if (lstEmployeelist.Items.Count > 0)
{
for (int i = 0; i <= sourceItems.Count -1 ; i++)
{
Master item = sourceItems[i] as Master;
this.masterSellectedBindingSource.AddNew();
Master sitems = masterSellectedBindingSource.Current as Master;
sitems.Empno = item.Empno;
sitems.FirstName = item.FirstName;
newsource.Remove((Master)item);
}
if (sourceItems.Count > 0)
this.masterBindingSource.RemoveCurrent();
this.masterSellectedBindingSource.EndEdit();
lstSelectedEmployees.DataSource = masterSellectedBindingSource;
lstSelectedEmployees.DisplayMember = "FirstName";
lstSelectedEmployees.ValueMember = "Empno";
}
}
catch (Exception ex)
{
throw ex;
}
}
I believe the problem is with the way you iterate through sourceItems.
Because you are doing it using a for loop (presumably because you cannot do it with a foreach because you cant then modify the collection), when you remove say item 1 from the collection and add it to the 2nd list, item 2 and all items after move up 1.
So item 2 becomes the new item 1 and item 3 becomes item 2, etc, etc...
To fix this, when you decide to move an item you also need to decrease i by 1 (i--;) so that when the for loops round again and i is increased it is back to the same index.
IF you are moving ALL items and not only select items, then you should not use a for loop, use a while instead like this:
while (sourceItems.Count > 0)
{
// code here
}

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