Commands through an interface like Command Prompt - c#

I was wondering is there a way to run an input form a user as a command without using switch or if statements?
For example if I had a form that contained a 10 by 10 picture frame, and wanted to change its size to 100 by 100. Better yet, is there a way to use a string that is defined in code:
string newString = "";
then change the name of said string: newString = "newButton" + count;
This code would be used like so:
for (int count = 0; count < records) // Records being the count of records to be presented.
{
newString = "newButton" + count;
Button newString.ToString() = new Button();
} //Uses the newString to give ID name to the new buttons.
Some thing similar to this would be using java code to create a table for a servlet using the <tag> and the out_print command.

It seems like maybe you're looking for a Dictionary<T,T>. You could implement your loop idea like this:
var buttons = new Dictionary<string,Button>();
for (int count = 0; count < records)
{
newString = "newButton" + count;
var newButton = new Button();
buttons.Add(newString, newButton);
}

Related

Adding values to a list box from array WITH text

I'm adding values from a file to an array and then adding those values to a list box in a form. I have methods performing calculations and everything is working great, but I'd like to be able to use a loop and insert the year prior to the values I am inserting into the list box. Is there a way to use the .Add method and include a variable which will be changing in this? Something like populationListbox.Items.Add(i, value); if i is my loop counter? Code is below so I'd like first line in the list box to have the year I specify with my counter, followed by the population. Like this, "1950 - 151868". As of now it only displays the value 151868. Thanks!
const int SIZE = 41;
int[] pops = new int[SIZE];
int index = 0;
int greatestChange;
int leastChange;
int greatestYear;
int leastYear;
double averageChange;
StreamReader inputFile;
inputFile = File.OpenText("USPopulation.txt");
while (!inputFile.EndOfStream && index < pops.Length)
{
pops[index] = int.Parse(inputFile.ReadLine());
index++;
}
inputFile.Close();
foreach (int value in pops)
{
**populationListbox.Items.Add(value);**
}
greatestChange = greatestIncrease(pops) * 1000;
leastChange = leastIncrease(pops) * 1000;
averageChange = averageIncrease(pops) * 1000;
greatestYear = greatestIncreaseyear(pops);
leastYear = leastIncreaseyear(pops);
greatestIncreaselabel.Text = greatestChange.ToString("N0");
leastIncreaselabel.Text = leastChange.ToString("N0");
averageChangelabel.Text = averageChange.ToString("N0");
greatestIncreaseyearlabel.Text = greatestYear.ToString();
leastIncreaseyearlabel.Text = leastYear.ToString();
Like this?
int i = 1950;
foreach (int value in pops)
{
populationListbox.Items.Add(i.ToString() + " - " + value);
i++;
}
Your life will be a lot easier if you stop trying to program C# as if it were 1980s C and use the power of it's Framework:
var pops = File.ReadLines("USPopulation.txt").Select(int.Parse);
populationListbox.Items.AddRange(pops.Select((p,i) => $"{i} - {p}"));

C# Sorting, return multiple text file string entries line at a time

I have a C# console window program and I am trying to sort "File3" (contains numbers) in ascending and output lines from 3 text files.
So the outcome looks something like this:
===========================================================================
field1.....................field2.....................field3
===========================================================================
[FILE1_LINE1]..............[FILE2_LINE1]..............[FILE3_LINE1]
[FILE1_LINE2]..............[FILE2_LINE2]..............[FILE3_LINE2]
[FILE1_LINE3]..............[FILE2_LINE3]..............[FILE3_LINE3]
and so on...
At the moment, it kinda works I think but it duplicates the first two lines it seems. Could someone give an example of better coding please?
Here is the code that I have atm:
string[] File1 = System.IO.File.ReadAllLines(#"FILE1.txt");
string[] File2 = System.IO.File.ReadAllLines(#"FILE2.txt");
string[] File3 = System.IO.File.ReadAllLines(#"FILE3.txt");
decimal[] File3_1 = new decimal[File3.Length];
for(int i=0; i<File3.Length; i++)
{
File3_1[i] = decimal.Parse(File3[i]);
}
decimal[] File3_2 = new decimal[File3.Length];
for(int i=0; i<File3.Length; i++)
{
File3_2[i] = decimal.Parse(File3[i]);
}
decimal number = 0;
for (double i = 0.00; i < File3_1.Length; i++)
{
for (int sort = 0; sort < File3_1.Length - 1; sort++)
{
if (File3_1[sort] > File3_1[sort + 1])
{
number = File3_1[sort + 1];
File3_1[sort + 1] = File3_1[sort];
File3_1[sort] = number;
}
}
}
if (SortChoice2 == 1)
{
for (int y = 0; y < File3_2.Length; y++)
{
for (int s = 0; s < File3_2.Length; s++)
{
if (File3_1[y] == File3_2[s])
{
Console.WriteLine(File1[s] + File2[s] + File3_1[y]);
}
}
}
}
Just for more info, most of this code was used for another program and worked but in my new program, this doesn't as I've said above - ("it repeats a couple of lines for some reason"). I'm kinda an amateur/ rookie at C# so I only get stuff like this to work with examples.
Thanks in advance :)
Ok, if I understand correctly, what you are trying to do is read the lines from 3 different files, each of them representing a different "field" in a table. You then want to sort this table based on the value of one of the field (in you code, this seems to be the field which values are contained in File3. Well, if I got that right, here's what I suggest you do:
// Read data from files
List<string> inputFileNames = new List<string> {"File1.txt", "File2.txt", "File3.txt"};
decimal[][] fieldValues = new decimal[inputFileNames.Count][];
for (int i = 0; i < inputFileNames.Count; i++)
{
string currentInputfileName = inputFileNames[i];
string[] currentInputFileLines = File.ReadAllLines(currentInputfileName);
fieldValues[i] = new decimal[currentInputFileLines.Length];
for (int j = 0; j < currentInputFileLines.Length; j++)
{
fieldValues[i][j] = decimal.Parse(currentInputFileLines[j]);
}
}
// Create table
DataTable table = new DataTable();
DataColumn field1Column = table.Columns.Add("field1", typeof (decimal));
DataColumn field2Column = table.Columns.Add("field2", typeof (decimal));
DataColumn field3Column = table.Columns.Add("field3", typeof (decimal));
for (int i = 0; i < fieldValues[0].Length; i++)
{
var newTableRow = table.NewRow();
newTableRow[field1Column.ColumnName] = fieldValues[0][i];
newTableRow[field2Column.ColumnName] = fieldValues[1][i];
newTableRow[field3Column.ColumnName] = fieldValues[2][i];
table.Rows.Add(newTableRow);
}
// Sorting
table.DefaultView.Sort = field1Column.ColumnName;
// Output
foreach (DataRow row in table.DefaultView.ToTable().Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
Now, I tried to keep the code above as LINQ free as I could, since you do not seem to be using it in your example, and therefore might not know about it. That being said, while there is a thousand way to do I/O in C#, LINQ would help you a lot in this instance (and in pretty much any other situation really), so I suggest you look it up if you don't know about it already.
Also, the DataTable option I proposed is just to provide a way for you to visualize and organize the data in a more efficient way. That being said, you are in no way obliged to use a DataTable: you could stay with a more direct approach and use more common data structures (such as lists, arrays or even dictionaries if you know what they are) to store the data, depending on your needs. It's just that with a DataTable, you don't, for example, need to do the sorting yourself, or deal with columns indexed only by integers. With time, you'll come to learn about the myriad of useful data structure and native functionalities the C# language offers you and how they can save you doing the work yourself in a lot of cases.

Input string was not in a correct format - calculating total of labels

Basically the first for statement below creates a list of testvalue labels depending on the user input.
The second for statement is supposed to work out the total of the dynamic labels created but when i play it i get an error saying "Input string was not in a correct format." relating to tots += double.Parse(value[p].ToString()); Any help would be appreciated. Thanks
ArrayList value = new ArrayList();
int p =0;
for (int i = 0; i < weight.Count; i++)
{
Label test = new Label();
System.Drawing.Point l8 = new System.Drawing.Point(440, 48 + s);
test.Location = l8;
value.Add(test);
k += 35;
Label l2 = testpercent1[i] as Label;
Double.TryParse(l2.Text.Trim(), out label2);
Label l = testpercent2[i] as Label;
Double.TryParse(l.Text.Trim(), out label1);
Double testvalue = Math.Round(((label1 * .3) + (label2 * .4)));
test.Text = testvalue.ToString();
}
Double total = 0;
for (int p = 0; p < value.Count; p++)
{
tots += double.Parse(value[p].ToString());
}
tots += double.Parse(((Label)value[p]).Text);
value[p] is of type Label. If you want to get the text value of the label, you should use value[p].Text.
Double total = 0;
for (int p = 0; p < value.Count; p++)
{
tots += double.Parse(((Label)value[p]).Text);
}
Another thing, you should use List<Label> for value instead of ArrayList.
You are trying to parse the ToString() of a label. Were you instead looking to parse some property of the label?
When you call value[p], whats being returned is a on object of type Label. If you wanted to parse the text of the label your code would instead be
tots += double.Parse(((Label)value[p]).Text);
Storing your data in labels is a very bad idea. Use a data structure that is better suited for this purpose like an array or a list of doubles. Only use the lables for displaying the data.
double[] values = new double[N];
Label[] lables = new Label[N]; // Only for display!
// Calculate (just as an example)
double result = values[i] + values[k];
// NOT LIKE THIS!
double result = Double.Parse(labels[i]) + Double.Parse(labels[k]);
It's obvious you are adding a control to the ArrayList. So this don't work:
tots += double.Parse(value[p].ToString());
I reccomend you to do:
value.Add(test.Text);
Then:
tots += double.Parse(value[p]);
PS:
Please use a List<string> instead of an ArrayList.

C# Is Creating a Dynamic StringBuilder Array Possible?

I am trying to dynamically create a StringBuilder array in C# and I haven't had much luck.
I want to add information to a StringBuilder (sb) based off of a given client digit that will change dynamically depending on how many clients I might have. I might have 2 or I might have 20. The sb will be used to build a report based per client later in my program.
For example I have the following 3 clients:
Client A = 0
Client B = 1
Client C = 2
If Client A is reporting he has 8 apples I want to add the string "8 apples" to sb[0].
If Client B is reporting he has 3 oranges I want to add the string "3 oranges" to sb[1].
The above is just a simple example of the idea I am trying to accomplish. In reality I am going to be adding a lot of information to the sb.
I have tried the following without much luck getting them to work they way I expected or wanted.
StringBuilder[] sbFileError = new StringBuilder[clientCount];
List<StringBuilder> sbFileError = new List<StringBuilder>();
Any thoughts? Is it possible to create a StringBuilder array?
Thanks!
You've created the containers above, but you need to fill them with something. For example:
StringBuilder[] sbFileError = new StringBuilder[clientCount];
for (int ix = 0; ix < clientCount; ++ix)
sbFileError[ix] = new StringBuilder();
Or
List<StringBuilder> sbFileError = new List<StringBuilder>();
for (int ix = 0; ix < clientCount; ++ix)
sbFileError.Add(new StringBuilder());
Creating the array is the first step, but this only creates places to store StringBuilders. You haven't actually instantiated any StringBuilders at this point. You'll need to do something like this....
StringBuilder[] sbFileError = new StringBuilder[clientCount];
for (int i = 0; i < sbFileError.Length; i++)
sbFileError[i] = new StringBuilder();
I think you are missing instantiation of array elements.
This code works.
int clientCount = 3;
StringBuilder[] sbFileError = new StringBuilder[clientCount];
for(int i=0; i<clientCount; i++)
{
sbFileError[i] = new StringBuilder();
}
sbFileError[1].Append("Hello World!");
List<StringBuilder> sbFileError = new List<StringBuilder>();
Looks OK, but you have to fill it:
for (int i = 0; i < numClients; i++)
sbFileError.Add(new StringBuilder());
You could also get fancy:
var items = Enumerable.Range(0, clientCount)
.Select(i => new StringBuilder());
var list = new List<StringBuilder>(items);
or shorten it to:
var list = Enumerable.Range(0, clientCount)
.Select(i => new StringBuilder())
.ToList();
Just another egg in the basket.

UserControlArray in Specific ButtonControlArray in C#

I am new to C#.I have been thinking of adding a ButtonControlArray where i can store each button control.Here is part of my code.I am creating a 6*6 array of button Control.
ButtonControl buttonControl;
ButtonControl[,] arrayButtons = new ButtonControl[6,6];
public void createGrid()
{
l = 0;
for (int i = 0; i < numberOfButtons; i++)
{
for (int k = 0; k < numberOfButtons; k++)
{
buttonControl = new ButtonControl();
buttonControl.Location = new Point(l,j);
j += 55;
arrayButtons[i, k] = buttonControl;
//After the above statement if i print Console.WriteLine(""+arrayButtons[i,k]); i am getting only my projectname.buttoncontrol
myGridControl.Controls.Add(buttonControl);
}
l += 55; j = 10;
}
}
I want to access each variable in arrayButtons[][]..like in a 3*3 matrix..if i want 2nd row 1 column element..then i get something like arrayname[2][1]..same way if i want 2nd button in 2nd row how can i get..i tried doing one way but i couldnt figure it out...Can you help me out with this..
What are you having difficulty with?
If you're running into bounds checking problems, you should know that C# arrays start at zero, not one. So the button in the second row, first column is a[1,0] not a[2,1]
If you Google Control Arrays in C# you will get several good matches, including this one.

Categories