Get a single string out of a ListBox Item - c#

I have a ListBox with X Items in it. An Item is build up like String, double, double. I want that the item with the smalles value of the second double gets shown together with its string in a Label.
An example Item: Name Value1 Value2
So every part is devided by spaces. The code works only for getting the smallest value of the second double yet, but doesnt take the string of that item.
The function of vName doesn't work.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
int anzahl = listBox.Items.Count;
string str = listBox.Items[anzahl].ToString();
string vName = str.Substring(0, str.IndexOf(" ") + 1);
var numbers = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').First(), NumberStyles.Currency, CultureInfo.CurrentCulture));
decimal minValue = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)).Min();
lVergleich.Content = vName + " " + minValue + "€";
}
}
Any ideas how I can get the string too?

I will try using your code example. You could use the old school approach and run with a for-loop through all entries.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
List<decimal> tmpListe = new List<decimal>();
int anzahl = listBox.Items.Count;
for (int i = 0; i < anzahl; i++)
{
string str = listBox.Items[i].ToString();
// collect all the second double values
tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture));
}
// get the minimal value and its index
decimal minValue = tmpListe.Min();
int index = tmpListe.IndexOf(tmpListe.Min());
// use the index to get the name
string str2 = listBox.Items[index].ToString();
string vName = str2.Substring(0, str2.IndexOf(" ") + 1);
// write down your comparison
lVergleich.Content = vName + " " + minValue + "€";
}
}
This should display you the first lowest value in your List.
personally I would also suggest to use a custom class with 3 properties and an overridden ToString method for display. Then collect all the items in a generic List and bind this List to the ListBox.

You can sort your collection by the desired value and take the first element in sequence
List<string> list = listBox.Items.ToList();
list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1])));
string x = list.First();
Or just
string result = listBox.Items.OrderBy(y => decimal.Parse(y.Split(' ')[1])).First();

Related

Check the value exists in List using C#

I have List as mentioned below. Now When I am going to add new string value into this list, My method GetNewCopiedValue has to check the new text value into the list lstNames.If the name does not exist in the list it should return the value as it is. If the new string value is exist already in the list, it has to return the string with respective index number as like EC(1).For example, If I am sending EC(1) again to the list, the method has to check the value in the list and It should return EC(3) since EC(1) is exist already in the list, the method has to check the similar values and it should return the value with next index number which is not there in the list.
Main()
{
List<string> lstNames=new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames,EC(2));
Console.WriteLine("Copied Text is :"+copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames,string sourceLabel)
{
label = sourceLabel;
if (lstNames.Any(i => i.Equals(sourceLabel)))
{
var labelSubstring = sourceLabel.Substring(0, sourceLabel.Length - 2);
var sameNameList = lstNames.Where(i => i.Contains(labelSubstring)).ToList();
int count = sameNameList.Count+1;
label = labelSubstring + count + ")";
while (lstNames.Any(i => i.Equals(label)))
{
var indexLabel = sourceLabel.Substring(sourceLabel.Length-2,1);
var maxIndex = sameNameList.Max(i =>int.Parse( i.Substring(sourceLabel.Length - 2, 1)));
int labelCount = maxIndex + 1;
label = labelSubstring + labelCount + ")";
}
}
return label;
}
Actual Input:
EC(2)
Expected output:
EC(3)
I have tried with some logic but it was not working with all input strings. It worked for few cases only.
Please help me on this.
https://dotnetfiddle.net/dFrzhA
public static void Main() {
List<string> lstNames= new List<string>{"Ecard","EC","EC(1)","EC(2)","NCard(1)"};
var copiedValue= GetNewCopiedValue(lstNames, "EC(1)");
Console.WriteLine("Copied Text is :" + copiedValue);
}
public static string GetNewCopiedValue(List<string> lstNames, string ValueToCopyInList) {
string newName;
if (!lstNames.Contains(ValueToCopyInList)) {
newName = ValueToCopyInList;
} else {
int? suffix = ParseSuffix(ValueToCopyInList);
string baseName = suffix == null ? ValueToCopyInList : ValueToCopyInList.Substring(0, ValueToCopyInList.LastIndexOf('('));
suffix = suffix ?? 1;
newName = baseName + "(" + suffix + ")";
while (lstNames.Contains(newName)) {
suffix++;
newName = baseName + "(" + suffix + ")";
}
}
lstNames.Add(newName);
return newName;
}
public static int? ParseSuffix(string value) {
int output;
if (string.IsNullOrEmpty(value)) return null;
if (!value.EndsWith(")")) {
return null;
}
var idxStart = value.LastIndexOf('(');
var strResult = value.Substring(idxStart + 1, value.Length - (idxStart + 2));
if (int.TryParse(strResult, out output))
return output;
return null;
}

convert number index of string array to double array

I am reading from a text file, pulling each line, looking for the first line with 1|, and then converting it into an array. For this I only want the 4th index so that I can sum and count the array.
Here is what is converts from the text file into an array
1|123456|01/06/2019|123456|100.00|USD|DUE UPON RECEIPT|TEST1||98790125|TEST2|TEST3|N
so [0] = 1, [2] = 123456, etc. etc. I am trying to pull 100.00 from it and put it in it's own array, so that I can easily double sum, and count the elements. It's proving difficult for me since the original array is a string though.
I've tried creating a separate string array already split, and then pulling the 4th index and creating an double array that I can count and sum. I've also tried just splitting and creating an int array in one line from the str it pulls.
string str;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
double[] itotals = strArray.Select(i => Convert.ToDouble(i)).ToArray();
int count = itotals.Length;
double amt = itotals.Sum();
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}
I expect it to find the line starting with 1|, then tell console to write count: 1 amt: 100.00, but I actually just get errors that input strings were not in the correct format. I know that I need to pull the 4th index after I split, but I'm not sure where to do that.
Try this
string str;
int count = 0;
double amt = 0;
using (StreamReader file = new StreamReader("c:\\testdoc.txt"))
while ((str = file.ReadLine()) != null)
{
string[] strArray = str.Split('|');
if (strArray[0] == "1")
{
string itotals = strArray[4];
count = count+1;
amt = amt + Convert.ToDouble(strArray[4]);
Console.WriteLine("Count: " + count + " Amt: " + amt);
}
else
{
}
}

c# regular expression getting specific string from string[CLOSE]

help i want to get the specific string from my string x="Glass 1 1000"; i want to get the string "Glass" only and save it to my string type.
int[] quanvalue = new int[2];
int x1 = 0;
string type = "";
string x="Glass 1 1000";
string[] numbers = Regex.Split(x, #"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int ib = int.Parse(value);
quanvalue[x1] = ib;
MessageBox.Show(quanvalue[0].ToString() + " " + quanvalue[1].ToString());
x1++;
}
else
{
// i want to get string from here
}
string sub = x.Substring(0, 5);
You can use a substring function to fetch the first 5 characters from x.
And save it in x itself

Input String was not in a correct form

There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();
You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.
If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0
First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.
the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....
Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.

Add numbers in c#

i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.
int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...
Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:
int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
int result = parsed + 2;
string add = result.ToString();
// Use add here
}
else
{
// Indicate failure to the user; prompt them to enter an integer.
}
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.
const int addend = 2;
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
doubleArray[index] =
Char.GetNumericValue(myTextBoxText.ToCharArray()[index])
* (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add =
(doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
string add=(int.Parse(mytextbox.Text) + 2).ToString()
if you want to make sure the conversion doesn't throw any exception
int textValue = 0;
int.TryParse(TextBox.text, out textValue);
String add = (textValue + 2).ToString();
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
String add = (intValue + 2).ToString();
}
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
private int MyTextBoxInt
{
get
{
return Int32.Parse(mytextbox.Text);
}
}
And then you can use the property like this:
int result = this.MyTextBoxInt + 2;

Categories

Resources