Check if Combo box is empty C# - c#

I am trying to check if a combo box is empty using C# in a Windows Application Form. Below are two possible ways:
if (string.IsNullOrEmpty(comboBox1.Text))
if (comboBox1.SelectedIndex == -1)
In order to ensure that the user would ONLY select a value from the drop down and NOT write it s own answer, which is the best approach?
From my research the second method (if (comboBox1.SelectedIndex == -1)) will satisfy my needs. Am l right?

If your concern is only making sure that users choose an item from the list available, simply change your combobox's DropDownStyle to DropDownList
or if you want to allow them to type but then ensure it is on the list, you can do something like this:
var txt = comboBox1.Text;
if(string.IsNullOrEmpty())
return;
var test = comboBox1.Items?.OfType<string>().ToList().Any(x => x?.Trim() == txt?.Trim());
so if test is false, it means what they have selected/typed does not exist in list of available items

for combobox you can use this code below to check if it's empty or not
if(comboBox1.Items.Count == 0 )
{
// your code
}

This is what i try and it 's work. Feel free to comment:
if (comboBox1.SelectedIndex > -1 )

Related

How to find a nested selenium WebElement in C# with LINQ?

I've been learning about LINQ and am trying to apply it to finding certain web elements on the page with selenium.
I have an angular site which displays a table made up of divs. All the rows in a column, including the header, have the same attributes (e.g. css selector/classname etc).
I want to find all the input boxes within a column that are visible, and came up with this...
var applyBoxes2 = from box in driver.FindElements(By.CssSelector("div.col-apply.col-md-1"))
where box.Text != "Apply?"
select box;
var clickableBox = from box in applyBoxes2
where box.FindElement(By.TagName("input")).Displayed == true
select box.FindElement(By.TagName("input"));
The first query is required as the first row is the header, and doesn't contain an input field. If I don't have this query my second query will fall over when trying to do the findelement = "input".
Does anybody know if I can combine these 2 statements? So first I would filter out the header, then I would find each input box within each div.
Any thoughts on how else this could be improved on would be welcomed.
Many thanks,
Use the && operator, it short circuits when it doesn't pass the 1st statement. So in your case it won't try to find an element if the text is Apply?.
var clickableBox = from box in driver.FindElements(By.CssSelector("div.col-apply.col-md-1"))
where box.Text != "Apply?" && box.FindElement(By.TagName("input")).Displayed == true
select box.FindElement(By.TagName("input"));
You can do something like this
var clickableBox = driver.FindElements(By.CssSelector("div.col-apply.col-md-1"))
.Where(box => box.Text != "Apply?")
.Select(box => box.FindElement(By.TagName("input")))
.Where(boxElement => boxElement.Displayed);
You can use let clause,
to perform inner clause.
Code will be like this:
var applyBoxes2 = from box in driver.FindElements(By.CssSelector("div.col-apply.col-md-1"))
let clickableBox = box.FindElement(By.TagName("input"))
where box.Text != "Apply?" && clickableBox?.Displayed = True
select clickableBox;

Count number of checkbox checked

I have multiple individual checkbox's (50).
like this:
<asp:CheckBox runat="server" ID="chkBirthDate" />
I need to know how many checkbox the user has selected (Count). If he has selected more than 3 i let him pass if not i present him an error message.
Thanks in advance!
LINQ Approach
You could take advantage of the querying capability of LINQ by using the OfType<T>() method to grab all of your individual CheckBox Controls and then use a Count() call to see how many were actually checked :
// Get the number of CheckBox Controls that are checked
var checkedBoxes = Form.Controls.OfType<CheckBox>().Count(c => c.Checked);
// Determine if your specific criteria is met
if(checkedBoxes > 3)
{
// You shall pass!
}
else
{
// None shall pass
}
You'll need to ensure that you have a reference to LINQ for this to work as well by including the following using statement :
using System.Linq;
Iterative Looping Approach
Alternatively, you could simply loop through and increment a count accordingly via a foreach loop as seen below :
// Store your count
var checkedBoxes = 0;
// Iterate through all of the Controls in your Form
foreach(Control c in Form.Controls)
{
// If one of the Controls is a CheckBox and it is checked, then
// increment your count
if(c is CheckBox && (c as CheckBox).Checked)
{
checkedBoxes++;
}
}
Example (with output)
You can find a GitHub Gist that fully reproduces this here and demonstrated below :

How can I check a DropDownList for containing item in asp.net

I am transfering my program from a WPF to ASP.Net.
I want to check a DropDownList if it contains a Item which I did in WPF this way.
else if (!_cbSlot3.Items.Contains("Jump") && !_cbSlot4.Items.Contains("Jump"))
{
foreach (string s in Stats2)
{
_cbSlot3.Items.Add(s);
_cbSlot4.Items.Add(s);
}
}
Simply it checks if it does not contain Jump in the 2 DropDown's.
Visual Studio tells me that it want a ListItem instead of a string now when doing this.
ListControl.Items is ListItemCollection, so to check for values you indeed need to use property of ListItem similar to:
!_cbSlot3.Items.Cast<ListItem>().Contains(v => v.Value == "Jump")
Note that ListItemCollection.Contains searches for value and text of ListItem where you seem to want to check just value. See ListItem.Equals for comparison details.
You can use inbuilt function for DropDownList, those are FindByValue and FindByText. MSDN
You can use it like this - _cbSlot3.Items.FindByValue("jump") != null or _cbSlot3.Items.FindByText("jump") != null .

set combobox text from textbox

I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.

How do I allow the user to multi-check with the CheckedListBox through the 'shift' key?

Say that I have a CheckedListBox with items "1", "2", "3", "4", and "5" in that order and I want to select "2", "3", and "4" by selecting "2" then holding shift and selecting "4". Is there any built-in way to achieve this with the CheckedListBox control? I found an article on how to use the SelectedIndexChanged event to get close to this behavior, but though it checks multiple items, it does not show them as selected.
http://www.windowsdevelop.com/windows-forms-general/multiple-selection-checkbox-53049.shtml
If there is an alternative control that I could use then I would be up for that as well.
There might be an easier alternative, but you could use a ListView, set CheckBoxes to true, HeaderStyle to None, and View to List.
Correction:
Should have been set View to Details.
Multiple selection is not supported, but i got here by search to find the CheckedItems.
The selected items refers to the items that are marked, the checked items refers to the items that are checked.
Hence use .CheckedItems property instead of .SelectedItems if you want the items with a checked checkbox.
for the multichecks i came up with this today:
List<int> listBox2_selectionhistory = new List<int>();
private void checkedListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
int actualcount = listBox2_selectionhistory.Count;
if (actualcount == 1)
{
if (Control.ModifierKeys == Keys.Shift)
{
int lastindex = listBox2_selectionhistory[0];
int currentindex = checkedListBox2.SelectedIndex;
int upper = Math.Max(lastindex, currentindex) ;
int lower = Math.Min(lastindex, currentindex);
for (int i = lower; i < upper; i++)
{
checkedListBox2.SetItemCheckState(i, CheckState.Checked);
}
}
listBox2_selectionhistory.Clear();
listBox2_selectionhistory.Add(checkedListBox2.SelectedIndex);
}
else
{
listBox2_selectionhistory.Clear();
listBox2_selectionhistory.Add(checkedListBox2.SelectedIndex);
}
}
as far as i know checkedlistboxes' SelectionMode can only be either one or none which means you can never make the app select more than 1 at a time (I also used this behavior to simplify my code for checkedlistboxes)
It looks like multiple selection is not supported for the CheckedListBox control (See MSDN). It does support multiple checkboxes being checked, but not multiple items being selected (highlighted) at once.
I agree with the other answer that a ListView is probably the best way to get both checkboxes and multiple selection.
It appears that it it not possible to set see the remarks section in CheckedListBox.SelectionMode Property
For an easier alternative follow the adivice of adrift.
private System.Windows.Forms.CheckedListBox LBO1;
string mySentLst = string.Join(";", LBO1.CheckedItems.Cast<string>());
Please follow these steps:
Select CheckOnClick = true.
When you want to retrieve selected item, use GetItemChecked(int index) method instead.

Categories

Resources