How to output only a part of values from ListBox? - c#

I would like to output only a part of items from listBox1 like:response.response.items[counter].first_name to lable_name.Text. How can I do that?
Part of method:
for (int counter = 0; counter < response.response.items.Count; counter++)
{
listBox1.Items.Add(response.response.items[counter].first_name + " " + response.response.items[counter].last_name + Environment.NewLine);
}
The way I output items to lable:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
int count = listBox1.Items.Count -1;
for (int counter = count; counter >= 0; counter--)
{
if (listBox1.GetSelected(counter))
{
lable_name.Text= listBox1.Items[counter].ToString();
}
}
}

lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];
could be one of the options ...
just make sure what charackter are qou spliting on as well as the text in string.

Related

Trying to generate a fibonacci sequence into a listbox item

private void btn_Click(object sender, EventArgs e)
{
int quantity = Convert.ToInt32(txtseq.Text);
int[] array = new int[lbox.Items.Count];
if (txtseq.Text.Length > 0)
{
for (int i = 2; i < array.Length; i++)
{
array[0] = 0;
array[1] = 1;
array[i] = array[i--] + array[i];
lbox.Items.Add(array[0].ToString() + array[1].ToString() + array[i].ToString());
}
}
else
MessageBox.Show("Insert something first");
}
Trying to generate a fibonacci sequence and sending it to a listbox item however i dont understand why its not being added to the listbox as a item in the for

Display only Even numbers in C#, using Windows Forms

I think this is a very easy answer and I understand that you enter something like this get an even number:
if (i % 2 == 0)
But I am just struggling to figure out how to slot it into my current code that I have here...
I have a form like so:
I am double clicking the 'Show Numbers' button
And I want the user to click the show numbers button and it only spits out even numbers, regardless if the box is checked or not.
namespace CHECK_BOXES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
if (checkBox1.Checked)
{
for (int i = 1; i <= 20; i++)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
else
{
for (int i = 20; i >= 1; i--)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
}
}
}
Would appreciate any help.
Thank you
Try with this function:
public bool IsEven(int value)
{
return value % 2 == 0;
}
and then update your for each loop with the following statement:
for (int i = 1; i <= 20; i++)
{
if (IsEven(i))
{
textBox1.Text += i.ToString() + "\r\n";
}
}
Or just easily increment i in for loop with 2.
Just do "double"-steps.
for (int i = 0; i <= 20; i += 2) { // <- pay attention, i will be incremented by 2
textBox1.Text += i.ToString() + "\r\n";
}
could be one line with Linq
textBox1.Text = string.Join("\r\n", Enumerable.Range(0, 20)
.Where((_, index) => index % 2 == 0).Select(x => x));

How to randomly generate 1000 sequences of 6 digit number

I want to generate 1000 number randomly and put the result in a rich text box ,but the result I got from my code is just one number appearing in the rich text box !!
private Random _random = new Random();
int min = 000000;
int max = 999999;
string s;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
}
You are overriding the value of s each time you get your next number. Instead you have to add the number to a list. Something like this would work.
List<string> numbers = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
numbers.Add(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = string.Join(Environment.NewLine, numbers);
}
As most of the answers here using the .net class Random i would not use it, because in a direct comparison it doesn't creates strong random numbers.
Example:
So if you want strong random numbers you should refrain from using Random and use the RNGCryptoServiceProvider from the namesapace System.Security.Cryptography
ExampleCode:
private RNGCryptoServiceProvider _random = new RNGCryptoServiceProvider ();
int min = 000000;
int max = 999999;
private void Form1_Load(object sender, EventArgs e)
{
int[] results = new int[1000];
var buffer = new byte[4];
int min = 100000;
int max = 999999;
for (int i = 0; i < results.Length; i++) {
while(results[i] < min || results[i] > max)
{
_random.GetBytes(buffer);
results[i] = BitConverter.ToInt32(buffer, 0);
}
richTextBox1.Text += results[i].toString();
}
}
You actually need to concatenate the result with previous calculated result, right now it is replacing the string value in s every time loop executes and you end up only with the last value in s, a quick fix is to use contatination using +:
for (int i = 0; i < 1000; i++)
{
s+= _random.Next(min, max).ToString("D6") + "\n"; // now it keeps previous values as well
}
Problem is that you actually overwrite at each iteration the string s. You need to append the number to the old ones.
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
You could also use AppendText method
for (int i = 0; i < 1000; i++)
{
richTextBox1.AppendText(_random.Next(min, max).ToString("D6") + "\n");
}
Suggestion by Matthew Watson: When generating such a large string it is very adviseable to use a StringBuilder. Is has much better performance than a normal concatenation of strings:
StringBuilder sb = new StringBuilder(8000);
for (int i = 0; i < 1000; i++)
{
sb.AppendLine(_random.Next(min, max).ToString("D6"));
}
richTextBox1.Text = sb.ToString();
s += _random.Next(min, max).ToString("D6") + "\n";
^
|
---- You're missing this plus sign
on this line of code you override the Text of richTextBox1
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
just change it to (add a + after s)
for (int i = 0; i < 1000; i++)
{
s += _random.Next(min, max).ToString("D6") + "\n";
}
richTextBox1.Text = s;
Note that the maxValue or Random.Next is exclusive, so 999999 is never genereted.
var numbers = Enumerable.Repeat(new Random(), 1000)
.Select(r => r.Next(1000000).ToString("D6")); // the same new Random() instance is used for all .Next
richTextBox1.Text = string.Join("\r\n", numbers);
Or a bit more efficient:
richTextBox1.Text = Enumerable.Repeat(new Random(), 1000).Aggregate(new StringBuilder(7000)
, (b, r) => b.AppendFormat("{0:D6}\n", r.Next(1000000))).ToString(0, 6999);
just You need to add ' + ' for the richtextbox1 as like below
try this one
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 1000; i++)
{
s = _random.Next(min, max).ToString("D6") + "\n";
richTextBox1.Text + = s;
}
}

Delete Duplicates From Text File Using Array

This is my code but I'm not sure what to put in a certain area (see below) as I keep getting an error there. I am basically loading up a text file and then deleting any values that are repeated and then outputting the updated copy of the text file.
The text file looks like,
5
5
3
2
2
3
My code is
{
public partial class Form1 : Form
{
//Global Variable
int[] Original;
public Form1()
{
InitializeComponent();
}
//Exit Application
private void mnuExit_Click_1(object sender, EventArgs e)
{
this.Close();
}
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//Code to Load the Numbers From a File
OpenFileDialog fd = new OpenFileDialog();
//Open the File Dialog and Check If A File Was Selected
if (fd.ShowDialog() == DialogResult.OK)
{
//Open File to Read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
//Go Through Text File
for (int i = 0; i < Records; i++)
{
Original[i] = int.Parse(sr.ReadLine());
}
}
}
private void btnOutput_Click(object sender, EventArgs e)
{
//Store Original Array
string Output = "Original \n";
//Output Original Array
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
//Create TempArray
int[] TempArray = new int[Original.Length];
//Set TempArray Equal to Original Array
for (int i = 0; i < Original.Length; i++)
{
TempArray[i] = Original[i];
}
//Current Index
int Counter = 0;
//Loop Through Entire Array
for (int i = 0; i < TempArray.Length; i++)
{
for (int j = i + 1; j < TempArray.Length; j++)
{
//Replace Duplicate Values With '-1'
if (TempArray[i] == TempArray[j])
{
TempArray[j] = -1;
Counter++;
}
}
}
//Set Size of Original Array
Original = new int[Original.Length - Counter];
//Counter = 0;
//Remove -1 Values
//error begins here
for (int i = 0; i < Original.Length; i++)
{
for (int j = i + 1; j < Original.Length; j++)
{
//Set Original Array Equal to TempArray For Values Not Equal To '-1'
if (j != -1)
{
Original[j] = TempArray[j];
//Counter++;
}
}
}
//error ends here
//Final Output -- The New Array
Output = Output + "Original Without Duplicates\n";
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
lblOutput.Text = Output;
}
}
}
I understand your logic, but wer'e all lazy programmers. You could simply use LINQ in order to prevent duplication. Load the array as you did already and use the Distinct method somthing like this:
int[] newArray = Orginal.Distinct().ToArray();
Goodluck.

Using two for-loops

This is an easy question but I'm still learning this language.
How we can write program that has parameters so that if the the number is 5, it will write
*
**
***
****
*****
I can do this:
*
*
*
*
Using this:
private void button1_Click(object sender, EventArgs e)
{
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m < numericUpDown1.Value; count)
{
message += "*" + "\r\n";
}
}
}
I think I need the second for-loop, but I'm not sure what to do next.
if that's not a conceptual homework it would be much easier to solve this way:
for(int i=1; i<=n; i++)
Console.WriteLine(new string('*',i));
You need two loops (see note).
First (a) counts from 1 to 5.
Second (b) counts from 1 to a and adds a "*" each time.
private void button1_Click(object sender, EventArgs e)
{
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m < count; m++)
{
message += "*";
}
message += "\r\n"
}
}
Note You can do it with one for loop. But personally I think the two loop version is clearer.
private void button1_Click(object sender, EventArgs e)
{
string line = "";
string message = " ";
for (int count = 0; count < numericUpDown1.Value; count++)
{
line += "*";
message += "\r\n" + line;
}
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
string message = "";
for (int count = 0; count < numericUpDown1.Value; count++)
{
for (int m = 0; m <=count ; m++)
{
message += "*" ;
}
message += "\r\n";
}
}
Yo do not need two for-loops, try this instead
private void button1_Click(object sender, EventArgs e)
{
string message = "";
for (int count = 1; count < numericUpDown1.Value + 1; count++)
{
message += "".PadLeft(count,'*') + Environment.NewLine;
}
}
Try this, just another way to do it for learning:
private static void PrintStars(int num)
{
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}

Categories