How can i generate a listbox algorithm? - c#

I have 2 textboxes for my list box.
start number and
finish number
I typing numbers and press "Aktar" button, then I want to add to listbox like below but how can I do that
I want to get a result like below

Adding numbers from start number to end number to ListBox:
private void btnAktar_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
var a = int.Parse(textBox1.Text);
var b = int.Parse(textBox2.Text);
var s = string.Empty;
for (var x=a;x<=b;x++)
{
s += x.ToString();
listBox1.Items.Add(s);
}
var chars = s.ToCharArray();
Array.Reverse(chars);
var reversedS = new string(chars);
for(var i = 1; i < reversedS.Length; i++)
{
var item = reversedS.Substring(i, reversedS.Length - i);
listBox1.Items.Add(item);
}
}
Result:

Related

Windows form - Make array to stop when there is no more data

Hello guys I am new to coding, and new to arrays as well and I was wondering how can I make this code to stop when there is no more names in the array, and from stop saying the number 10 always before the names. As well to show the position of the names one number above, not just starting from 0, but from 1.
Here is what I have so far.
string[] list = new string[10];
int pos = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string StudentName;
StudentName = textBox1.Text;
list[pos] = StudentName;
pos++;
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(list.GetLength(0).ToString());
string message;
for (int i = 0; i < lista.GetLength(0); i++)
{
message = "";
message = "The student" + " " + list[i] + " has the position " + i ;
MessageBox.Show(message);
}
}
Use a dynamic array, aka List<T>
List<string> list = new List<string>();
Instead of manually keeping track of the position, just add the item to the end:
list.Add(StudentName);
You can check the number of current items in the list by using .Count.
for (int i = 0; i < list.Count; i++) {...}
But you can also use a foreach loop to iterate over all the items in the list, but this way you do not get the position automatically.
foreach(var item in list){...}
For the sake of completeness, another way would be to filter out empty entries.
Linq is especially great for working with Enumerables like these:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-6.0
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] list = new string[10];
list[0] = "test1";
list[1] = "test2";
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
// Filter out null, an empty string or only whitespace characters from the array
list = list
.Where(c => !string.IsNullOrWhiteSpace(c))
.ToArray();
Console.WriteLine("==========================");
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
}
}
https://dotnetfiddle.net/g7e0Nm
First you can specify the maximum capacity of your array using a const
const int arrayCapacity = 10;
string[] list = new string[arrayCapacity];
int pos = 0;
Then you should add some validation if the array is full, according to your maximum capacity, and/or if the textbox is empty.
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Textbox was empty");
return;
}
if (pos > arrayCapacity - 1)
{
MessageBox.Show("Array is full");
textBox1.Clear();
return;
}
list[pos] = textBox1.Text;
pos++;
textBox1.Clear();
}
And the last step is to create a new array in any case you have a smaller number of students than your initial array's capacity
private void button2_Click(object sender, EventArgs e)
{
var arr = list.Where(x => !string.IsNullOrEmpty(x)).ToArray();
for (int i = 0; i < arr.Length; i++)
{
string message = "The student" + " " + arr[i] + " has the position " + (i + 1);
MessageBox.Show(message);
}
}

Get specific listview rows based on condition

I have a listview with diffrent entries (see figure (A). I would like to extract some specific rows based on a condition. So far, i have this code:
private void Button2_Click(object sender, EventArgs e)
{
ArrayList listing = new ArrayList();
for (int i = 0; i < listView2.Items.Count; i++)
{
string columnOne = listView2.Items[i].Text;
string columnTwo = listView2.Items[i].SubItems[1].Text;
int numb = int.Parse(listView2.Items[i].SubItems[2].Text);
string columnThree = listView2.Items[i].SubItems[3].Text;
if(numb >= 2)
{
listing.Add($"{columnOne},{columnTwo},{numb},{columnThree}");
}
}
foreach (string item in listing)
{
listView2.Items.Clear();
ListViewItem listItem = new ListViewItem();
var separ = item.Split(',');
listItem.Text = separ[0].Trim();
listItem.SubItems.Add(separ[1]);
listItem.SubItems.Add(separ[2]);
listItem.SubItems.Add(separ[3]);
listView2.Items.Add(listItem);
}
}
I get figure (B), but normally i should get figure (C). How can this be achieved?
you shouldn't clear listview in foreach loop. do it once:
listView2.Items.Clear();
foreach (string item in listing)
{
// listView2.Items.Clear();
ListViewItem listItem = new ListViewItem();
var separ = item.Split(',');
listItem.Text = separ[0].Trim();
listItem.SubItems.Add(separ[1]);
listItem.SubItems.Add(separ[2]);
listItem.SubItems.Add(separ[3]);
listView2.Items.Add(listItem);
}
Removing the non matching items from the list makes more sense here. For your problem, execute a backward loop, try to convert the text of the third subitem to integer value using the int.TryParse method, and remove the ListViewItem if the value is less than 2.
private void button2_Click(object sender, EventArgs e)
{
for (var i = listView2.Items.Count - 1; i >= 0; i--)
{
if (int.TryParse(listView2.Items[i].SubItems[2].Text, out var num) && num < 2)
{
listView2.Items.RemoveAt(i);
}
}
}
Yet, if you want to get a list of matching items:
// +
using System.Collections.Generic;
private void button2_Click(object sender, EventArgs e)
{
var items = new List<ListViewItem>();
for (var i = 0; i < listView2.Items.Count; i++)
{
if (int.TryParse(listView2.Items[i].SubItems[2].Text, out var num) && num >= 2)
{
items.Add(listView2.Items[i]);
}
}
// ...
}
Or LINQ way:
// +
using System.Linq;
private void button2_Click(object sender, EventArgs e)
{
var items = listView2.Items.Cast<ListViewItem>()
.Where(x => int.TryParse(x.SubItems[2].Text, out var num) && num >= 2)
.ToList();
// ...
}
As a side note, using the ArrayList class is not recommended, use the List<T> class instead.

How can I find the sum of the elements within a ListBox in WPF

How can I find the sum of the elements within a ListBox. I just need to find a way to store the sum of the values of the ListBox and output once the users inserts the wrong input
private void theMethod(object sender, RoutedEventArgs e)
{
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else {
String[]arr = new String[3];
// I just want to be able to output the sum of the elements of the ListBox (MyListBox)
for ( i = 0; i < MyListBox.Items.Count; i++)
{
//MyListBox.Items[i].ToString();
MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString();
}
sum.ToString();
MessageBox.Show("Sum is: " +MyListBox.Items.Cast<ListBoxItem>().Sum(x => Convert.ToInt32(x)).ToString());
}
The problem of your code is here:
MyListBox.Items.Cast<ListBoxItem>
To calculate sum of items of your list box, if you are sure that they are integer numbers that added as int or string, you can use this snippet:
var sum= this.ListBox1.Items.Cast<object>()
.Select(x => Convert.ToInt32(x))
.Sum();
MessageBox.Show(sum.ToString());
The above code assumes that you add items to ListBox using such code:
var value= this.TextBox1.text;
//your logic for null checking and ...
this.ListBox1.Items.Add(value);
Here is the complete code that I test based on your codes.
While you are adding integer values to listbox, we don't need Cast<object> and Select(x=>Convert.ToInt32(x)) anymore and its enough to Cast<int> like below:
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result);
}
else
{
var sum = this.MyListBox.Items.Cast<int>().Sum();
MessageBox.Show(string.Format("Sum is: {0}", sum));
sum.ToString();
}
InputTextBox.Text = String.Empty;
this worked for me , try this :
private void YesButton_Click(object sender, RoutedEventArgs e)
{
int sum = 0;
int i = 0;
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
// Do something with the Input
String input = InputTextBox.Text;
int result = 0;
if (int.TryParse(input, out result))
{
MyListBox.Items.Add(result); // Add Input to our ListBox.
}
else
{
sum = MyListBox.Items.Cast<int>().Sum(x => Convert.ToInt32(x));
MessageBox.Show("Sum is: " +sum);
}
// Clear InputBox.
InputTextBox.Text = String.Empty;
}

I am trying to display the number of occarances of a letter, but the output only shows the last letter

I am trying to print a list of occurrences of each letter in thee text inputed by the user but the textbox only shows the last letter.
private void button1_Click(object sender, EventArgs e)
{
//disable the text box so text cannot be entered until reset is pressed
textBox3.Enabled = false;
//make a list containing the alphabets
List<string> Alphabets = new List<string>();
Alphabets.Add("A");
Alphabets.Add("B");
Alphabets.Add("C");
Alphabets.Add("D");
Alphabets.Add("E");
Alphabets.Add("F");
Alphabets.Add("G");
Alphabets.Add("H");
Alphabets.Add("I");
Alphabets.Add("J");
Alphabets.Add("K");
Alphabets.Add("L");
Alphabets.Add("M");
Alphabets.Add("N");
Alphabets.Add("O");
Alphabets.Add("P");
Alphabets.Add("Q");
Alphabets.Add("R");
Alphabets.Add("S");
Alphabets.Add("T");
Alphabets.Add("W");
Alphabets.Add("X");
Alphabets.Add("Y");
Alphabets.Add("Z");
//make a while loop to cycle through alphabets loop
int i = 0;
while (i < Alphabets.Count)
{
//assign value in the list Alphabets
string SearchFor = Alphabets[i];
//access textbox and make it to upper small small and captital are the same
string SearchIn = textBox3.Text.ToUpper();
//list to count the number of instances used for each letter
List<int> FoundCount = Search(SearchFor, SearchIn);
//if statement so only letters that occor more than 0 times are displayed
if (FoundCount.Count > 0)
{
//string to display the number of occorances
//convert to toString so it can be displayed in the TextBox
string Counts = Alphabets[i] + ": " + FoundCount.Count.ToString();
//create a message box to display the output
//MessageBox.Show(Counts);
textBox4.Text = String.Join(Environment.NewLine, Counts);
}
//adds 1 each time as long as i <alphabet.count
i++;
}
}
//List takes 2 arguements (SearchFor, SearchIn) Results can be passed to FoundCounts and number of occrances can be calculted
List<int> Search(string Target, string Subject)
{
//List to count the number of occarances for each letter
List<int> Results = new List<int>();
//for loop for comparison (counting occarances) to compare each letter in textbox to each letter in alphabets
for (int Index = 0; Index < (Subject.Length - Target.Length) + 1; Index++)
{
//if to calculate the number of times a letter is used.
if (Subject.Substring(Index, Target.Length) == Target)
{
//adds the number in index to the list Result
Results.Add(Index);
}
}
return Results;
}
i made multiline as true but that didnt work
I'm pretty sure the issue with your code is here:
textBox4.Text = String.Join(Environment.NewLine, Counts);
You're overwriting the text every time, instead you should do:
textBox4.Text += String.Join(Environment.NewLine, Counts);
This isn't a direct answer to the question, but this might be valuable for the OP.
This code does everything that the original code did (and also fixes the issue raised in the question):
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var query =
from c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let count = SearchIn.Count(x => x == c)
select String.Format("{0}: {1}", c, count);
textBox4.Text = String.Join(Environment.NewLine, query);
}
There you go, a version that uses lists. :-)
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList();
var query =
from c in alphabet
let matches = SearchIn.Where((x, n) => x == c).ToList()
select String.Format("{0}: {1}", c, matches.Count());
textBox4.Text = String.Join(Environment.NewLine, query);
}

Converting strings to int in C#

im pretty new to C# and i want to make a cardgame. What i have is a list of cards (strings) with names like c6, s3, h11, d13 where the character represents the colour and the number represents the value. When pressing a button the program takes a random string from the list and displays it in a textbox. From there the point of the game is to guess if the next random card will have a higher value or a lower value then the previous card.
What i want to do is to take the string from the textbox and turn it into a int so that i can compare the value of the previous card with the new one. Only problem is how do i get rid of the c in c6 so i can convert it by using parse.
This is my code.
public partial class MainWindow : Window
{
static Random rndmlist = new Random();
Random rndm = new Random();
List<string> deck = new List<string>();
int score = 0;
public MainWindow()
{
InitializeComponent();
}
private void test_Click(object sender, RoutedEventArgs e)
{
//disregard this
foreach (string j in deck)
{
testbox.Text += j + ", ";
}
}
private void btnstart_Click(object sender, RoutedEventArgs e)
{
//this is where i add all the cards to the list
for (int i = 1; i <= 13;)
{
deck.Add("c" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("s" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("h" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("d" + i);
i++;
}
}
private void btnbegin_Click(object sender, RoutedEventArgs e)
{
//this is where i take a random card from the list and display it in textBox2
int r = rndmlist.Next(deck.Count);
textBox2.Text = ((string)deck[r]);
//disregard this
testbox.Text += ((string)deck[r]) + ", ";
deck.Remove((string)deck[r]);
}
private void btnhigh_Click(object sender, RoutedEventArgs e)
{
//this is where i want to compare the cards.
}
}
Thank you in advance for reading this. (:
I'd better create a class Card, which represents a card, with 2 properties: Color and Number and implemented method Card.ParseFromString()
Try this,
string SubString = MyString.Substring(1);
But take care if the string is empty, it is an error case.
Assuming there will always be one (and only one) character before the number, you can simply do this:
string numberAsString = "c2".Substring(1);
And to make that an int:
int number = Int32.Parse(numberAsString);
You can use Regex to replace all alpha characters eg
string result = Regex.Replace(myString, #"[a-zA-Z\s]+", string.Empty);
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);

Categories

Resources