Combobox with Textbox content issue - c#

I am running into an issue when using a textbox as the content of a combobox in WPF. When I have some items in the combobox already and then enter an extension of one of those items in the textbox, the textbox clears itself when it matches one of the existing items. An example:
The combobox contains the following:
'test1'
'test2'
I then attempt to enter the value 'test23'. When I get to 'test2' the matching value in the combobox is highlighted. When I proceed to type the '3' in 'test23', the textbox is cleared and all I am left with is a '3'. Obviously this is not a desired behavior.
I've looked through the configurable properties on microsoft's documentation pages and I haven't been able to find a property or combination that allows me to disable this behavior. Does anyone know what's going on here as well how I might fix it? Thanks.

If your are trying to add extension text to your default text in combobox items, try in code behind to declare the text items as a stringbuilder and use the property Append as follow
Code behind:
System.Text.StringBuilder text = new System.Text.StringBuilder();
TextBox textitem = new TextBox();
text="set the default text you want";
textitem.text=text;
Combobox.items.add(textitem);
text.append("the extension text you want");
Hope it helps.

Related

Unable to set Text in Combox Box in DropDownList

I want to set the text in a combo box. Below is the code-
private System.Windows.Forms.ComboBox selectModel;
this.selectModel = new System.Windows.Forms.ComboBox();
this.selectModel.Name = "selectModel";
this.selectModel.FormattingEnabled = true;
this.selectModel.Size = new System.Drawing.Size(64, 21);
this.selectModel.Location = new System.Drawing.Point(3, 76);
this.selectModel.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
The following line is not working-
selectModel.SelectedText = getModelNameFromConf();
The documentation says that "it Gets or sets the text that is selected in the editable portion of a ComboBox". I can't make it editable to user.
Any workaround please.
This is because when you use ComboBoxStyle.DropDownList, the dropdown has no editable portion. To make it editable, use ComboBoxStyle.DropDown.
Note too the remarks on the SelectedText property relating to whether the control has focus. You may find the Text property more suitable for many purposes.
EDIT For example:
selectModel.Text = getModelNameFromConf();
Assuming the combo contains that value in its list, setting Text will also set the SelectedIndex property of the dropdown.
(I think some of the property names of this control are particularly confusing, including DropDown vs. DropDownList. Someone at MS had a bad day when this control was coded. Note also that the word selection is being used in two different ways: here, you want to set the selected item, whereas SelectedText means some text that is selected—which might not be the whole of the item text. This is the same as in a textbox where the user has dragged the mouse to highlight some of the text but not all of it.)

How can I populate ComboBox edit field with ValueMember but show DisplayMember in the list?

I have an editable ComboBox with a validation on the Text property to make sure manually entered info is valid.
EDIT: All I want to do is populate the .Text property with the ValueMember of a selection rather than the DisplayMember
I also have the .Items populated with valid entries having the DisplayMember and ValueMember set.
My DisplayMember is a caption along with the data, and the ValueMember is the data itself.
So Items might be:
(DisplayMember, ValueMember)
"Foo - 1ab2" , "1ab2"
"Bar - 3cd4" , "3cd4"
I had a validation on the text which can also validate manual user input like "5ef6"
The problem I'm having is that if the user selects an item from the combobox it populates the text field with the DisplayMember property (ex: "Foo - 1ab2") which will fail validation.
I have tried to manually set the .Text property with the SelectedValue or the SelectedItem.Value on each of the three relevant combobox events to no avail.
I would like that the .Text of the ComboBox get populated with the .ValueMember of the item when selected rather than the .DisplayMember
EDIT: I cannot validate by trying to extrapolate the value from the caption. I send the Text off to a service to be validated.
void FillMyCombo
{
KeyValuePair<string, string> listValue1 = new KeyValuePair<string, string>("Foo - 1ab2" , "1ab2")
KeyValuePair<string, string> listValue2 = new KeyValuePair<string, string>("Bar - 3cd4" , "3cd4")
myCombo.Items.Add(listValue1);
myCombo.Items.Add(listValue2);
myCombo.DisplayMember = "Key";
myCombo.ValueMember = "Value";
}
...
void myCombo_TextUpdated
{
if(!myValidationService.Validate(myCombo.Text))
{
do error stuff
}
}
The user can manually enter something like "5ef6" which will pass validation.
But when they select an item from the list, rather than manually entering it, the .Text property gets filled with the caption and not the value ... so it will contain "Foo - 1ab2" and that will fail validation.
EDIT: In response to an answer posted: I cannot change the validation method to "infer" the value from the caption. I have no control over that service. All I'm after is the displayed value
EDIT: Say a user selects "Foo - 1ab2" from the dropdown list, I want the text in the box to say "1ab2"
EDIT: I have also tried to set the .Text property in code but I can't seem to make it work in any of the ComboBox events. If anybody can answer how to programmaticly set the .Text property (and make it commit!) on a selection event they will also answer this question.
What about http://nickstips.wordpress.com/2010/11/19/c-datagridviewcomboboxcolumn-displaying-different-values-in-drop-down-list/ -- they change ValueMember and DisplayMember on the fly upon dropdown opening/closing.
Example is for DatagridViewComboBox. A ComboBox has those events, too, no?
Give it a try and downvote if it does not help :)=
** Update **
Another good-looking solution might be ArgumentException when adding ComboBox column to DataGridView with same DataSource, there look at the not-accepted answer.
Simply validate the .SelectedText property of the ComboBox instance. .Text will always contain what the user sees, i.e. the display property's value:
void myCombo_TextUpdated
{
if(!myValidationService.Validate(myCombo.SelectedText))
{
do error stuff
}
}
SelectedText gets or sets the text that is selected in the editable portion of a ComboBox, I think even if SelectedIndex=-1/SelectedValue=Null.

C# Datagridview: get selected item in combobox columns

I'm working on a GUI that allows the user to manipulate xml files. I display the xml file in a datagridview organized neatly by columns through xml elements. I allow the user to add columns as an extention on my project. The column gets added to the dataset table, then updated to the datagridveiew that I use to display the xml file in. I've included the ability for the user to add a combobox column to select choices instead of entering them in constantly like.. true or false. However, that is where the problem lies. Saving a normal column was easy. The combobox column is being a pain.
I have a "save combobox column" to have it updated to the xml and a "save" button to save in a destination of the user's choice.
I've done some research and it seems like the combobox class has such a feature to gain access to the selecteditem in the combobox put in by the user.
Where we have:
ComboBox box = new ComboBox();
box.SelectedItem;
I tried applying this to the combobox column class but it does not have such a function. Thus, I cannot figure out how to directly obtain the value of the user's selected item. I tried experimenting with comboboxcell's as well, but that didn't lead me anywhere either. Both those classes I played around with do not have a... "selected item" function and even google does not have a solution for me. =( I've also tried using the cell.value, but it is "null" for some reason. Even when the user selects an item in the box, it doesn't get saved into the cell's value.
TLDR:
My question in short is, how, if possible, do you gain access to the comboboxcolumn cell's selected item? Additionally, how would you then ensure that the item value is saved in the cell?
Thanks in advance. I'm using .NET 3.5 SP1, through Visual Studio 2008 C#.
Sincerely,
tf.rz
The Control in a DataGridView is not a ComboBox, it is a DataGridViewComboBox and has different properties and methods. From MSDN
Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.
However, you mentioned that the Cell.Value is null for you. Well there may be another step you are missing according to the following article (How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List).
You must set the DataGridViewComboBoxColumn.ValueMember or DataGridViewComboBoxCell.ValueMember property to the name of a property on your business object. When the user makes a selection, the indicated property of the business object sets the cell Value property.
If we have bound a datagridcomboboxcell with a different DisplayMember and ValueMember, like so:
dgcombocell.DisplayMember = "Name";
dgcombocell.ValueMember = "Id";
dgcombocell.DataSource = dataset1.Tables[0];
Then for getting SelectedText, and SelectedValue, we can write this code:
string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());
int SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);
I hope it solves your problem.
Use this to get or set selected value:
object selectedValue = currentRow.Cells["comboboxColumnName"].Value
Don't forget to set DisplayMember and ValueMember for your DataGridViewComboBoxColumn
This is how it is done
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dgv.Rows[0].Cells[1];
MessageBox.Show(""+comboCell.Items.IndexOf(comboCell.Value));
A .Net combox is actually a composite control made up of a textbox and a dropdownlist. Use box.Text to get the currently displayed information.
EDIT: The row or the cell should have a .FindControl() method. You'll need to do something like:
Combobox box = (Combobox)(row.FindControl("[combobox ID]"));
string val = box.Text;
Basically, you're finding the control within its container (row or cell), then casting the control found as a combobox, then accessing its .Text property.
I use this:
private int GetDataGridViewComboBoxCellSelectedIndex(DataGridViewCell d)
{
return ((DataGridViewComboBoxCell)d).Items.IndexOf(d.Value);
}

Combobox population problem

So I have a combobox - the designer code:
this.cmbStatusBox.Items.AddRange(new object[] {
"Ordered",
"Cooking",
"In-transit",
"Delivered"});
The formload code:
if (mainForm.boolEdit == true)
{
this.cmbStatusBox.Items.AddRange(new object[] {
"Cooking",
"In-transit",
"Delivered"});
}
else
{
this.cmbStatusBox.Items.AddRange(new object[] {
"Ordered"});
}
As you can see, I am trying to make the combobox have different values.
As things stand, i get both whats in the designer and in formload in the comboboxes.
How can i stop this?
I also have an edit function, so when i edit a record, i want the combo box to be populated by what is already saved.
Just a random question, can you stop the user entering a value that isn't in the combo box?
Thankyou
If you want to replace the current contents then you'll need to call
this.cmbStatusBox.Items.Clear();
before adding your new values.
ComboBox MSDN page
ComboBox.Items MSDN page
The DropDownStyle property also specifies whether the text portion can be edited.
Source
The values are:
Simple Specifies that the list is always visible and that the text portion is editable. This means that the user can enter a new value and is not limited to selecting an existing value in the list.
DropDown Specifies that the list is displayed by clicking the down arrow and that the text portion is editable. This means that the user can enter a new value and is not limited to selecting an existing value in the list. When using this setting, the Append value of AutoCompleteMode works the same as the SuggestAppend value. This is the default style.
DropDownList Specifies that the list is displayed by clicking the down arrow and that the text portion is not editable. This means that the user cannot enter a new value. Only values already in the list can be selected. The list displays only if AutoCompleteMode is Suggest or SuggestAppend.
Source
Just remove the items from the designer code.

How do I set a ComboBox default *not in the drop down* when a list item begins with the same text as a drop down item?

Using C#, say you have a ComboBox that has a DropDownStyle set to DropDown (there are items in the drop down but the user can manually enter a value as well). How do you set a default value for the ComboBox that is not in the list of values in the drop down, but begins with text from a possible selection? Normally setting ComboBox.Text works fine, but if there is an item in the drop down that begins with the text you want as the default, it automatically selects the first item in the list that starts with the text. For example:
Values in the drop down:
c:\program files\
c:\windows\
d:\media\
Default Value Assignment
myComboBox.Text = "C:\";
Result
Initial value of ComboBox when the form opens is "c:\program files\".
So what am I doing wrong? How do I correctly set a default value of an item not in the drop down list that begins with a possible selection?
Does the following code work?
myCombo.SelectedIndex = myCombo.FindString(#"c:\");
Note: I haven't tried it. Looked up for properties/methods that could help using reflector.
I couldn't repro the behavior you are describing. Adding the three values via the Items collection and then setting the initial value to "c:\" (you omitted an # in your code sample, by the way) worked fine. My guess is that something else in your code is setting the value of the combo box after you set it.
I was able to get this to work with having the items in the ComboBox be ComboBoxItems (I dont see why this wouldn't work with other types). Set the ComboBox.Text like you are and make sure SelectedIndex = -1 and also you need IsEditable = True.

Categories

Resources