Check if combobox value is empty - c#

I have created a ComboBox with three values. I wanted that a message box opens when no item is selected so I tried this:
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Please select a value");
return;
}
That works fine but only if I click into the field in the combobox. When I dont touch it, the program will start without message box. Whats wrong?

if (string.IsNullOrEmpty(comboBox1.Text)) or if (comboBox1.SelectedIndex == -1)

Use
if (comboBox1.SelectedIndex == -1)
{
MessageBox.Show("Please select a value");
return;
}
Note: SelectedIndex will be set to -1 when SelectedValue is blank ONLY when FormattingEnabled is true. See here.

The code should work. Although I will also set SelectedIndex as well......
if (this.comboBox1.SelectedItem == null || this.comboBox1.SelectedIndex == -1)
you mean "When I dont touch it, the program will start without message box. Whats wrong?" is there any code related with "touch it"

Check the selected index value of dropdown equals -1
if (Comboboxid.SelectedIndex == -1){
MessageBox.Show("Your message.");
}

Ithink this is the one :
if(comboBox.SelectedItems==null) //or if(comboBox.SelectedItems==-1)
{
//show no item was selected from comboBox
}
or
if(comboBox.SelectedItems.Count==0)
{
//message no items selected
}

A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value. Conditionally testing SelectedItem or SelectedIndex will not handle the case of the user entering a new value from another input device like a keyboard. Use string.IsNullOrEmpty(comboBox1.Text) to handle all input/selection cases.

try this is the :
if ((comboBox.SelectedValue == null) || string.IsNullOrEmpty(comboBox.Text))
{
//message no items selected
}

Related

How to retain original value on cell edit of datagridview column?

I am having a grid which shows list of products with following columns :
ProductId,ProductName,MRP,FinalAmount
Now I have kept MRP as editable so that user can change it based on discount on some products.I have kept validation on MRP column to not allow user to enter null value but the problem is when I raised the validation message original MRP value is LOST.
So what I am trying to do is when user enter negative/null value then I want to show message and retain last MRP value.
Code :
private void grdProductList_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
if (grdProductList.CurrentCell == null ||
grdProductList.CurrentCell.Value == null ||
e.RowIndex == -1) return;
if (grdProductList.CurrentCell.ColumnIndex.Equals(3))//MRP
{
if(string.IsNullOrEmpty(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString()))
{
MessageBox.Show("MRP cannot be empty.Please provide value", "Error");
return;
}
decimal.TryParse(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString(), out decimal mrp);
if(mrp < 0)
{
MessageBox.Show("MRP cannot have negative value", "Error");
return;
}
grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["FinalAmount"].Value = mrp;
//calculation code based on mrp
}
}
I have found that DataGridView provides a method called CancelEdit which discards the changes and also helps to retain original value.
I just need to call this method like below and got the expected behaviour :
if(string.IsNullOrEmpty(grdProductList.Rows[grdProductList.CurrentRow.Index].Cells["MRP"].Value.ToString()))
{
MessageBox.Show("MRP cannot be empty.Please provide value", "Error");
grdProductList.CancelEdit();
return;
}
Store the MRP original value in a temp variable,
if user entered null or negative value, restore the temp value to current grid cell

Check if index of List<List<string>> is not null

I have a List<List<string>>, and a ComboBox with 10 items and when the selected index is changed, I use the comboBox_selectedIndexChanged event to bind the data for this index into a ListBox.
I also have Add and Remove buttons that can insert data to my List<List<string>.
How can I prevent the user from selecting index 5 from the ComboBox and add data for it, if the first four are still empty? E.g. tell him that he has to put data in indexes 1, 2, 3 and 4 first.
The click event for the Add button looks like this:
int selectedIndex = comboBox1.SelectedIndex;
//This throws an exception when the selected index is zero,
//of course it makes sense because we can't check if index 0-1 in myList is null
if (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null)
{
myList[selectedIndex].Add(textEdit1.Text);
}
else
MessageBox.Show("Please fill the previous indexes first.");
I know that I can do it in the SelectedIndexChanged event of the ComboBox, but I prefer to do it here.
What about:
int selectedIndex = comboBox1.SelectedIndex;
if (selectedIndex == 1 || (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null))
{
myList[selectedIndex].Add(textEdit1.Text);
}
else
MessageBox.Show("Please fill the previous indexes first.");
if selectedIndex == 1 is true then it wont test the second parameter in the if statement, and won't throw an error. If it is not 1 it will test the second parameter and your error will not be thrown.

How to find out if a ComboBox contains any items?

I have simple WinForms application in C# which has two controls: combobox1 and button. I would like to find out if there are any items in combobox1.
I have tried this, but it only tells me if there is a selected item:
if (combobox1.Text != ""))
{
MessageBox.Show("Combo is not empty");
}
Double click on your button in the Form and insert this code inside the click event handler : `
//this code should work
if (comboBox1.Items.Count == 0)
{
MessageBox.Show("Your combo is empty");
}
`
I use
if (comboBox1.SelectedItem!=null)
{
MessageBox.Show("Combo is not empty");
}
to determine if something is selected
And I use this to determine if the comboBox has any items.
if (comboBox1.Items.Count > 0)
{
MessageBox.Show("Your combo is not empty");
}
If no item selected/Present, then SelectedIndex property returns -1.
if (combobox1.SelectedIndex == -1)
//no item selected/present
Well, I am sure if you check out ComboBox class on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox_properties, it'd benefit you.
Also, personally I wouldn't tend to use selectedIndex or selectedItem property, as there can be a case where item collection is not empty but none of any items are actually selected. Use items.count is a better way to decide if item collection is empty or not.
if (ComboBox.Items!=null && ComboBox.Items.Count>0)
{
//have some item
}
and if you need to know how many item have Use
string Count = ComboBox.Items.Count;

how to check if item is selected from a comboBox in C#

I'm pretty new here.
I have a form, and want to check if the user filled it in correctly. In the form there's a combo box; how can I build the "if" statement for checking whether the user picked an item from it ?
P.S. Sorry for my bad English, it's not my mother tongue. :)
Use:
if(comboBox.SelectedIndex > -1) //somthing was selected
To get the selected item you do:
Item m = comboBox.Items[comboBox.SelectedIndex];
As Matthew correctly states, to get the selected item you could also do
Item m = comboBox.SelectedItem;
Here is the perfect coding which checks whether the Combo Box Item is Selected or not
if (string.IsNullOrEmpty(comboBox1.Text))
{
MessageBox.Show("No Item is Selected");
}
else
{
MessageBox.Show("Item Selected is:" + comboBox1.Text);
}
You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.
if (this.combo1.SelectedItem == MY_OBJECT)
{
// do stuff
}
if (comboBox1.SelectedIndex == -1)
{
//Done
}
It Works,, Try it
if (combo1.SelectedIndex > -1)
{
// do something
}
if any item is selected selected index will be greater than -1
You can try
if(combo1.Text == "")
{
}
I've found that using this null comparison works well:
if (Combobox.SelectedItem != null){
//Do something
}
else{
MessageBox.show("Please select a item");
}
This will only accept the selected item and no other value which may have been entered manually by the user which could cause validation issues.

C# How do I run some code for the selected item in a listbox?

I have a listbox of names, I want to click one of the names so that it is highlighted and then click a button that runs some code for the selected item. How do I call this selected item?
private void btnEcho_Click(object sender, EventArgs e)
{
listbox1.SelectedItem......
}
Many thanks
The listbox isn't very intuitive because it contains objects instead of something like ListItem, but if you just want the text you can do this:
string selectedText = listbox1.SelectedItem.ToString();
String s = listbox1.SelectedItem.Value.ToString();
Don't forget to do a null check, because this will throw an error if your list is empty or if no value is selected.
Listbox1.SelectedItem gets the actual selected item. You can then further call from SelectedItem to get other properties/methods such as SelectedItem.Text or SelectedItem.Value
If you wanted to make it all happen upon selection from the listbox (instead of pressing a button), you could just add a SelectedIndexChanged event for Listbox1 (and in ASP.NET make sure that AutoPostBack is set to TRUE)
string str = listbox1.SelectedValue.ToString();
here you have the what value(name) selected.
if(str == null || str == string.empty) return;
and so on. you can do whatever you want;
goodluck
You're question is not clearly to me.
Example, you have a listbox of three items: A, B and C.
You have, as you do with your example, a click-event. In that click-event you can use the switch-statement to handle some code for each item:
switch (listbox1.SelectedItem)
{
case "A":
// Code when select A
break;
case "B":
// Code when select B
break;
... (and so on).
}
Code is an example and not tested. See switch for more information.

Categories