How to disable items based on condition in combo box? - c#

Am developing a windows application in C#.
The user has to select some listed values in combo box. Those values will be added to Database. When the same user login and select the combo box, already selected values should be visible but shouldn't be get selected....
I referred various websites. All stating to change the colour of Existing values....But it is not enough. I need to disable the values... Is there any options to do it.
Note : Am populating the combo-box items from a database table.

You can set ComboBox.SelectedIndex = -1 for your desired value;
The code is not tested but something like this will help you
if (combobox.selectedIndex == (Index of your value))
{
combobox.selectedIndex = -1;
}
In this way if you try to choose that item it will set selected index to -1 and you will not able to choose that item.

The following link might be helpful for you
Create WinForms ComboBox with non-selectable items
While biding values from db set the selectable property true or false and in the selectedindexchanged event set the selectedindex of the item to -1.
Don't forget to mark it as answer if it is helpful for you.
Note: Before doing this make sure that it is required to show the items. If it is not required just filter them and bind the remaining values.

Related

Eliminate null entry in combobox

Is there any property to remove the first (and empty) item in a combobox with style DropDownList ? In other words, I would like to choose the default selected item for a combobox.
I know i can validate the selected item with code, but i want to avoid showing message boxes to the user.
Set the comboBox.SelectedIndex property to 0 to set the selection to the first item in the combobox.
You should set the Text or SelectedIndex or SelectedValue property. In this way the combobox updates the text that's is showing and removes the first empty item (that actually is not a real item).

How to deleselect / blank a databound ComboBox? SelectedIndex = -1 does not work

I am trying to deselect (blank out) a number of combo-boxes in my windows forms application. In my application I have a Reset method that sets the SelectedIndex for each combo to -1. All of my combo-boxes are databound, i.e. each combo-box is populated using a datasource.
I have noticed that sometimes my Reset method works, i.e. it deselects the currently selected item and blanks the combo. However, other times it chooses the first item (SelectedIndex = 0) straight after I attempt to set it to -1. From a users point of view this looks like a bug as it doesn't always "clear" the form.
According to MSDN:
"To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item."
Does anyone know of a work around?
Many thanks
Use combination of the void and property
comboBox.ResetText();
//to reset selected value
comboBox.SelectedIndex = -1;
Don't know if anyone is still interested in this, seeing as it's now 5 years later, but I found a very easy workaround. Totally non-intuitive (I only found it by looking at the reference source code), but trivial to implement:
ComboBox1.FormattingEnabled = True;
Yep, that's all there is to it!
If you're curious, you can peruse the source code to see what's going on. It appears that the root cause of the bug noted by #CuppM is the attempt to set the position in the data source:
if (!FormattingEnabled || SelectedIndex != -1) {
this.DataManager.Position = this.SelectedIndex;
}
I would guess that it should have simply been '&&' instead of '||' in the condition, as the code probably shouldn't be setting the Position to an invalid value regardless of the FormattingEnabled property.
In any case, it allows for a simple workaround. And since the default behavior if the 'Format' property is blank is a no-op, you don't have to change anything else. It just works. :-)
(I should note that I have only tried this with .NET 4.7, so I can't say whether it works for prior versions of the .NET Framework.)
You can try to set the Selected Value or Item to null (Nothing in VB)
I cant remember the behavior of throwing an exception. However, I do remember that I used to insert a value called -1, (None) to the combo-box after it was databounded usually through the databind events. I'd recommend get the data in a List and insert the new value to this list. Bind the combo to the List now.
Only the following code works for me, so try:
comboBox.ResetText(); //framework 4.0
ComboBox1.SelectedItem = null;
For anyone still looking at this old post I wanted to add a note from what Hisham answer.
Make sure to clear your list after inserting his code.
comboBox.ResetText();
//to reset selected value
comboBox.SelectedIndex = -1;
comboBox.Items.Clear();
Try assigning null or String.Empty to the SelectedValue property.
If your target framework is 4.0 - here is the solution:
Install .Net Framework 4.5 (do not change target framework of your project, just install the framework).
After installing, that line deselects databound combobox:
combobox.SelectedValue = 0;
My value member is "Id" int primary key auto-increment, so that field does not contain value 0.
However, that won't work on Windows versions, that do not support .net45
Try to set the [ComboBoxObj].SelectedIndex=-1; which will make it to empty value.
-1 refers to deselect or nullify the value of combobox
Thanks
I have had this problem for a while, but if you use:
'ComboBox.ResetText();'
it will make the text "" and leave the items in the combo box unaffected.
i used the following code in my application
private void UpdateComboBox(ComboBox Box, string Group, List<string> Numbers)
{
Box.Items.Clear();
Box.BeginUpdate();
Box.Items.Add("<<Add Contact>>");
foreach (string item in Numbers)
{
if(item != "")
Box.Items.Add(item);
}
Box.EndUpdate();
Box.ResetText();
}
So i run the method last, once all items are in the combo Box.
Try this line of code:
combobox1.Items.clear();
It works for me.
Add to your combobox one empty item, something like this:
cb.Items.Add("");
After this you can deselect your combobox by selecting the last cb item:
cb.SelectedIndex = cb.Items.Count - 1;
There you go!
You'll have the last place empty in your combobox, but it wont bother you. will it? :-)
I got the following error:
There is no row at position 0
when I was setting ComboBox.SelectedItem to -1.
Replacing by ComboBox.ResetText() worked OK. This was using .Net 4.6.1, with VS 2013 where TextFormatting = True by default for ComboBoxes.
you may try to use this solution..
dataGrid.DataSource = Nothing
dataGrid.DataBind()
hope its help!..:D

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