Check List Box before Adding New Item - c#

I am trying to check that an item doesn't already exist in a list box before I add the new item.
if (TeamNameTextBox.Text != "")
{
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
{
TeamNameListBox.Items.Add(TeamNameTextBox.Text);
TeamNameTextBox.Text = "";
int teamCountUpdate = TeamNameListBox.Items.Count;
if (teamCountUpdate == 1)
{
TeamCount.Text = teamCountUpdate.ToString() + " Team";
}
else
{
TeamCount.Text = teamCountUpdate.ToString() + " Teams";
}
}
else
{
AddTeamSeasonError.Text = "This team has already been added";
}
}
else
{
AddTeamSeasonError.Text = "Please select a team";
}
I have got it to check if the text box is blank, but I need to check that the item a user is trying to add is not already in the the list box.
I have tried the line:
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null)
But that doesn't work, any suggestions on how I can do the check?

Use this:
if (!TeamNameListBox.Items.Contains(TeamNameTextBox.Text))
TeamNameListBox.Items.Add(TeamNameTextBox.Text);

think you should at least try to use TeamNameTextBox instead of TeamNameListBox as argument
if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null)

I suppose you mean
// search if the textbox value is found in the list. this comment shouldn't be part of the code
if (TeamNameListBox.Items.FindByValue(TeamNameTextBox.Text) == null)
instead of
if (TeamNameListBox.Items.FindByValue(TeamNameListBox.Text) == null) // code from question
EDIT: There is no need to put the name of the type of the control next to the variable.
i.e. instead of TeamNameListBox, use teamNames. And, instead of TeamNameTextBox, use teamName.

Related

Else if statement inside for each loop - C#

I have a foreach loop like this where I want the else condition to output: "unit not found" if the quad.ID == searchForQuadcopters isn't found but I get this string value output even when the value is found.
foreach (var quad in allQuadcopters)
{
if (quad.ID == searchForQuadcopter)
{
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
WriteLine($"Capacity (kg): {quad.capacityKg}");
WriteLine($"Reach (km): {quad.reachKm}");
WriteLine($"Transponder ID: {quad.transponderID}");
quad.vehicleDeliveryForm();
}
else
{
WriteLine("Unit not found");
}
}
You won't know if the value isn't found unless you iterate over the ENTIRE list first and don't encounter it.
Create a boolean flag to track whether the value was found or not:
bool found = false;
foreach (var quad in allQuadcopters)
{
if (quad.ID == searchForQuadcopter)
{
found = true;
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
WriteLine($"Capacity (kg): {quad.capacityKg}");
WriteLine($"Reach (km): {quad.reachKm}");
WriteLine($"Transponder ID: {quad.transponderID}");
quad.vehicleDeliveryForm();
break; // if you don't want to iterate over the rest
}
}
if (!found) {
WriteLine("Unit not found");
}
I want the else condition to output: "unit not found" if the quad.ID == searchForQuadcopters isn't found
Then you don't want this loop. Your code loops over all items, and if allQuadcopters contains Ids 1, 2 and 3 and you're looking for 2, it will print "Unit not found" for Ids 1 and 3. You could break; out of the loop in your if(), but then the else will still be hit for 1.
You want to leverage Linq here:
var quad = allQuadcopters.FirstOrDefault(q => q.ID == searchForQuadcopters);
if (quad == null)
{
WriteLine("Unit not found");
}
else
{
WriteLine("Value found.");
// write here all the information you want to display.
WriteLine($"ID: {quad.ID}");
}

Unable to cast from string to generic list in C#

I have written a code to store uploaded image names into the session list.
A user can upload only 4 images, so there will be max 4 image names in a session.
A user can upload 1, 2, 3 or 4 images based on requirement. If a user selects only 2 images, the session will have only 2, so the rest 2 will throw index out of bound exception!
to handle such situation i have written following code.
string image1 = "";
string image2 = "";
string image3 = "";
string image4 = "";
var imageSessList = (List<string>)Session["Images"];
if (imageSessList != null)
{
for (int i = 0; i < imageSessList.Count; i++)
{
if (imageSessList[i] != null && i == 0)
{
image1 = imageSessList[i];
}
if (imageSessList[i] != null && i == 1)
{
image2 = imageSessList[i];
}
if (imageSessList[i] != null && i == 2)
{
image3 = imageSessList[i];
}
if (imageSessList[i] != null && i == 3)
{
image4 = imageSessList[i];
}
}
}
But now it's showing following error: "Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List"
How can I resolve it, or is there any way to complete this functionality.
The problem is that Session["Images"] doesn't contain a list but a string. You have to correct this on the setting side.
A general solution to prevent such errors is by wrapping the session state into a class, and using the typed properties from that class for getting and setting:
public static class SessionState
{
public List<string> Images
{
get
{
return HttpContext.Current.Session["Images"] as List<string>;
}
set
{
HttpContext.Current.Session["Images"] = value;
}
}
}
Now you can just get and set SessionState.Images.
From previously mentioned comments:
#StephanBauer i have written following lines in foreach: lstImageNames.Add(destFileName); context.Session["Images"] = lstImageNames; – ace 22 mins ago
If context.Session["Images"] = lstImageNames; is done in foreach loop, then you are overwriting the value in the session each time.
One more thing i wanted to point out is, string can not only be null but empty too. So, you may want to change your null checks as (just a suggestion):
if (!string.IsNulOrEmpty(imageSessList[i])l && i == 0)

How to use information from a scope elsewhere

I'd like to use the information gathered from ReadLine() in another code scope.
I've created a menu and I'm using an if-statement.
If I want to use the information gathered in option 1 in the menu, and write it into option 2, how do I go about doing that?
if (selectMenu == 1)
{
Console.WriteLine("What item will you put in the backpack?");
//Console.ReadLine();
string item = Console.ReadLine();
}
else if (selectMenu == 2)
{
}
So basically I want to be able to use item in the else if.
You could declare the variable in the outside scope:
string item = null;
if (selectMenu == 1)
{
Console.WriteLine("What item will you put in the backpack?");
item = Console.ReadLine();
}
else if (selectMenu == 2)
{
}
... you could use the item variable here but it will have its default value of null
if selectMenu was different than 1 because in this example we assign it
only inside the first if.

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.

Best way to check if a drop down list contains a value?

When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?
This is what I've attempted, but it doesn't return a bool.
if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) )
ddlCustomerNumber.SelectedIndex = 0;
There are two methods that come to mind:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new
ListItem(GetCustomerNumberCookie().ToString())))
{
// ... code here
}
or modifying your current strategy:
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != null)
{
// ... code here
}
EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.
That will return an item. Simply change to:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
If 0 is your default value, you can just use a simple assignment:
ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();
This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.
I use this mechanism quite a lot and find it very handy.
What about this:
ListItem match = ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString());
if (match == null)
ddlCustomerNumber.SelectedIndex = 0;
//else
// match.Selected = true; // you'll probably select that cookie value
On C# this works:
if (DDLAlmacen.Items.Count > 0)
{
if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
{
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
}
}
Update:
Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."
So. for this to work on Visual Basic, I had to change the code like this:
If DDLAlmacen.Items.Count > 0 Then
If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
End If
End If
ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}
You could try checking to see if this method returns a null:
if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
//you can use the ? operator instead of if
ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";
If the function return Nothing, you can try this below
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}
Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):
if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Categories