Creating listbox items from a large string - c#

I have a large string that contains text:
"value 1
value 2
value 3
etc..." //over 100 values
I am trying to create a listbox with it's items based on the values in this string.
I used a try catch as I was getting an argument out of range exception which stopped the error but I can't see any items in the listbox :P
string value = "";
int currentIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(listStr, "\r\n?"))
{
try
{
value = formatted.Substring(currentIndexPos, m.Index - 1); // -1 so the matched value isn't used.
listBox1.Items.Add(value);
currentIndexPos = m.Index + 1;
}
catch
{
//argument out of range exception
//Index and length must refer to a location within the string. Parameter name: length
}
}

As many have said, just use String.Split. However, there's no need for a foreach loop or resorting to LINQ, just do this:
listBox1.Items.AddRange(String.Split(...));

Try something like this
var values = listStr.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(string value in values)
{
listBox1.Items.Add(value);
}

Since you are in essence doing a split why not use that function and ignore the index operations.
var lst = String.Split("\r".ToCharArray(),"listStr");
lst.select((x)=>listBox1.Items.Add(x));

Related

How to use Split() for making a command system in c#

I want to do something like this:
string a = Console.Readline();
string[] b = a.Split(' ');
string i = b[0];
string j = b[1];
Now the problem is, putting the 'string j' may be optional like the input may be hi hello here hello is optional. How to make the code work if someone doesn't put something in place of hello.
Thanks in advance.
You could use the Length property to check how many elements are in the split array.
If there are not enough elements in the array to assign the optional value you can set it to null.
In the rest of your code you just have to null-check the optional value before using it.
Something liket his would work:
string input = Console.ReadLine();
string[] tokens = input.Split(' ');
string hi = tokens[0];
string optional = tokens.Length > 1 ? tokens[1] : null; // make sure we have enough elements
Console.WriteLine(hi);
// null check before using the optional value
if (optional != null)
Console.WriteLine(optional);
// or
Console.WriteLine(optional ?? "Optional value is null..");
Instead of accessing the arrays particular element by its index position, I would use foreach loop to iterate over a list like:
string a = Console.ReadLine();
string[] b = a.Split(' ');
foreach (string elem in b)
{
Console.WriteLine(elem); // Do whatever you want with each element
}
Console.ReadLine();
Since the "commands" entered by the user will be stored in the array (e.g. b based on your code) after the split, I don't think it's necessary to store them in individual variables yourself. Thus, avoiding the problem you have in your current setup. On the other hand, if you want to see if a specific "command" was keyed in, you can do something like this:
static void Main(string[] args)
{
Console.Write("> ");
string input = Console.ReadLine();
// Doing it like this will automatically remove blanks from the resulting array
// so you won't have to clean it up yourself
string[] commands = input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
// Contains is from the System.Linq namespace
// this will allow you to see if a given value is in the array
if (commands.Contains("hi"))
{
Console.WriteLine("> The command 'hi' has been received.");
}
Console.Read();
}
You can use Linq's Contains method to check if a specific value exists in the array of command strings.
if you just want to see all the commands in the array, a simple for loop would be enough.
// The Length property of the array will give you the
// number of items it contains
for(int i = 0; i < commands.Length; i++)
{
Console.WriteLine("> Command read: {0} ", commands[i]);
}
One more thing, I suggest that you normalize the inputs your application will receive as to avoid problems when filtering through them. You could do this by calling the ToLower method available to ReadLine:
string inputs = Console.ReadLine().ToLower();
Happy coding :)

how to convert a String list into a String array then converting it into an int array then counting the total sum of the numbers in the array?

So I am so fresh into the world of programming, starting new, I decided to start messing around in C# to create simple apps from ideas that come to mind, with this little app, I'm trying to have multiple TextBoxes named d1,d2,d3,d4,etc... the user inserts numbers into the textboxes then clicks button1, which begins the process in the code below creating a new list which contains all of the values of the textboxes and then the list is converted to an array and the array is then converted into an int array, etc....
BUT, when starting the application and I add values to the textboxes and then click button1, it shows 2 error like shows in the //gray code line below
Please help.
private void button1_Click(object sender, EventArgs e)
{
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
foreach(string numb in dodo)
{
if (numb == "")
numb = "0"; //numb word has a red underline
}
string[] terms = dodo.ToArray();
int[] valv = {};
int x = 0;
for(int i=0;i<=19;i++)
{
valv[i] = int.Parse(terms[i]); //the ; in the end has a red underline and shows "FormatException was unhandled" error
i++;
x = x + valv[i];
}
string myString;
myString = x.ToString();
Result1.Text = myString;
}
you can't change the iteration variable which is numb in your case. Please change in the List container instead
List<string> dodo = new List<string>();
dodo.Add(d1.Text); dodo.Add(d2.Text); dodo.Add(d3.Text); dodo.Add(d4.Text); dodo.Add(d5.Text);
dodo.Add(d6.Text); dodo.Add(d7.Text); dodo.Add(d8.Text); dodo.Add(d9.Text); dodo.Add(d10.Text);
dodo.Add(d11.Text); dodo.Add(d12.Text); dodo.Add(d13.Text); dodo.Add(d14.Text); dodo.Add(d15.Text);
dodo.Add(d16.Text); dodo.Add(d17.Text); dodo.Add(d18.Text); dodo.Add(d19.Text); dodo.Add(d20.Text);
int k = 0;
foreach (string numb in dodo)
{
if (numb == "")
{
//numb = "0"; //numb word has a red underline
dodo[k] = "0";
}
k++;
}
Now your code on parsing into integer won't give any runtime error.
The first line "tells" you that you are not able to assign a new value to the variable which is used as a foreach iteration variable.
The second line, "tells" you that you have string value which is not able to be parsed correctly (e.g. user put string which is not a number). To avoid this you can use Int32.TryParse method instead, which will safely try to parse the given string.
The best and easiest way to achieve what you need is using LINQ methods, here is the example based on few things/assumptions:
Since you are converting empty strings into zeros, you could simply skip those entries from counting
To avoid FormatException, you should use TryParse method instead. Since TryParse method will safely parse the given string, you don't even have to filter empty strings at all (they will be skipped). However, I deliberately left filtering part, to get you a better overview of a solution.
You can use list initializer to make list initialization more readable
Solution:
List<string> dodo = new List<string>()
{
d1.Text, d2.Text //...others
};
int sum = dodo
.Where(item => !String.IsNullOrEmpty(item))
.Sum(item =>
{
if (Int32.TryParse(item, out int parsedItem))
{
return parsedItem;
}
return 0;
});
You can get more familiar with LINQ and used methods on following link

if ListBox.SelectedIndex contains a number 1

Basically i'm trying to make it so if the Selected Index from a listbox (for example lets say the selected index is "Server1") contains a number ("1") or a certain word ("Server") it would do a certain thing. For example: If the selected index from the listbox contains a number 1, it would enter 1 into a text box. If the selected index contains a number 2, it would open up a application, just for an example.
what i tried:
if (csrListBox.SelectedIndex = "1");
and:
{
List<string> items = ListBox.Items.Cast<string>().ToList();
foreach (string item in ListBox.Items)
{
Regex regex = new Regex(#"1");
Match match = regex.Match(item);
if (match.Success)
{
*Doing Something*
}
}
ListBox.DataSource = items;
}
Try this:
if (csrListBox.SelectedIndex == 1);
The second "=" sign matters - it states you're doing a boolean check instead of assigning value "1" to the value.
Mistake - You are assigning value.
Use compare operator ==. and SelectedIndex is int not string.
if (csrListBox.SelectedIndex == 1)
{
// Your code goes here.
}
I would suggest you work with ListBox item values instead of selectedIndex as the SelectedIndex can only be an integer value. Something like this linq query will return if the ListBox contains a certain value that is selected. This takes care of multi-selections too.
var myValue = "1";
bool listContainsItem = ListBox.Items.Any(item => item.Value == myValue && item.Selected);

Using the value found through '.contains'

This is a console unit conversion program which takes in a measurement unit (such as pounds, ounces) specified by the user, followed by a second measurement unit, and finally a value to convert from one unit to the other.
string userUnit1, userUnit2 = "";
int userValue = 0;
The units that can be used are specified in a text file, the contents of which are split into a string array (called 'units') in the program. The text file also contains the 'conversion value' between the two units. In the text file, they appear like so: ounce,gram,28.0 (since there's 28 grams in one ounce, this value is also put into the array).
The units that the user enters are checked with the following snippet of code:
double result = 0;
if (units.Contains(userUnit1) && units.Contains(userUnit2))
{
//??? Something like:
//result = userValue */ value in the array element;
}
The basic IF statement above checks the array for the units that the user enters, and what I want to do is use the conversion value in that array element to convert the number that the user entered. How would I go about this?
EDIT: This is the code for storing the split text into the array.
using (read = new StreamReader("C:/Users/Sam Smith/Desktop/convert.txt"))
{
while (!read.EndOfStream)
{
lineFromFile = read.ReadLine();
lineFromFile.Split(' ');
foreach (int i in lineFromFile)
{
count++;
if (count % 3 == 0)
{
units.Add(lineFromFile);
}
}
}
}
Something like this?
String path = #"C:\Users\Sam Smith\Desktop\convert.txt";
var lines = System.IO.File.ReadLines(path)
.Where(l => l.Contains(userUnit1) && l.Contains(userUnit2));
if(lines.Any())
{
var unit = lines.First();
var parts = unit.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
var result = userValue * double.Parse(parts[2]);
}
You need a reference to the System.Linq namespace for Enumerable.Where. You can use File.ReadLines to retrieve all lines in a file as IEnumerable<string>.
Use the IndexOf method into unit1Index and unit2Index and compare to -1 to assure they were found, or use the FirstOrDefault extension method and compare to null.
It also sounds like you should make a dictionay out of it, which would simplify this with TryGetValue.
var conversionsDic = File.ReadAllLines("conversions.txt")
.Select(l => l.Split(' '))
.ToDictionary(ls => ls[0] + ls[1], ls => double.Parse(ls[2]));
double conversion;
if (conversionsDic.TryGetValue(userUnit1 + userUnit2, out conversion))
{
// use 'conversion' to do whatever
var result = userValue * conversion;
}

Array List Problem

How do I check for null in a array list and remove them? It keeps giving me a error of "ArgumentOutOfRange was handled" or if I change the SMTPException to just Exception it says "Index out of range". Looking at the debugger and taking a look specifically at mails.Count it gives me Count = 4. I originally gave it 3 emails to check. The last Array is a "". I believe this is causing the problem.
private void button1_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
// textBox1.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
// Grabs Emails supplied in textbox1 amd then seperates array using '\n'
ArrayList mails = new ArrayList(textBox1.Text.Split('\n'));
// Note: For thought
// IEnumerable<string> myResults = mails.Split('\n').Where<string>(s => !string.IsNullOrEmpty(s));
for (int i = 0; i < mails.Count; i++)
{
// Seperates user & pass to be passed for authentification.
ArrayList mailInfo = new ArrayList(mails[i].ToString().Split(':'));
textBox3.Text += "[+] Checking email format for" + "\r\n" + "[/] " + mails[i] + "\r\n";
// Attach domain name if not attached.
if (!mailInfo[0].ToString().EndsWith("#gmail.com")) mailInfo[0] = mailInfo[0] + "#gmail.com";
// Debug: Check point
//
// Error message:
// Index was out of range. Must be non-negative and less than the size of the collection. Parameter name index.
// mails.Count = 4 when feeding only 3 emails.
//
// Function: Check mail & Password
// error: index out of range
// MessageBox.Show(mailInfo[0].ToString() + "\n\n" + mailInfo[1].ToString());
if (mails[i] == "") throw new ArgumentOutOfRangeException("No Mail", "No more mail to check.");
if (checkAccount(mailInfo[0].ToString(), mailInfo[1].ToString()))
{
textBox3.Text += "[+] Connection Successful! Checking mail.: mailInfo[0].ToString()\r\n";
}
}
}
What am I doing wrong??? Is the null my problem and if so how do I remove it or am I missing something?
To remove items from a list by checking conditions can be tricky. If you're not using a nifty LINQ statement (since you're using an ArrayList im going to assume LINQ is not availiable to you) you will need to use reverse iteration.
If you iterate over a list like this:
foreach(object o in ArrayList)
{
}
Or
for(int i = 0; i < myArray.Count; i++)
{
}
You will run into issues removing items because you'll run out of items (since the list is now smaller than when you defined your for/foreach).
You need to use reverse iteration or store a list of items to remove later.
Example 1: Reverse Iteration
for(int i = myArray.Count - 1; i >= 0; i--)
{
object o = myArray[i];
if (<some condition here>)
myArray.Remove(i);
}
Example 2: Removal List*
ArrayList toRemove = new ArrayList();
foreach(object o in myArray)
{
if(<some condition here>)
toRemove.Add(o);
}
foreach(object o in toRemove)
myarray.Remove(o);
Example 3: LINQ Approach
var cleanEntities = myArray.Where(x => <some condition on x, which is your item>);
Try populating the array like this:
ArrayList mails = new ArrayList(textBox1.Text.Trim().Split('\n'));
That should remove any trailing white space and remove that last item from getting into the array.
I think the empty entry is caused by a carriage return after the last item in your textbox.
It's generally simpler to iterate over one list while building up another. Hard to go wrong that way.

Categories

Resources