Listing integers from a text file into a listview - c#

I'm creating an app in winforms c# using vs 2013.
In the app I have a textfile to which I'm saying the time in int format using a custom format from a time select dropdown list.
I then want to display what is in that text file on a selectable listview from where I can remove it from the textfile etc. I'm almost there however at the moment when I try to add the items into the listbox they do seem to add however they do not display correctly.
For example say in my text file there is
22102210
19101610
17182218
10272227
Then that is how it should be displayed in the listview as selectable ready to be deleted.
At the moment it isn't showing correctly, it's showing up as 1.. 2.. 1..
Could someone help me out and point me in the right direction as to why this might be happening? Any help much appreciated. This is my class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chronos
{
public partial class Interface : Form
{
private string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
public Interface()
{
InitializeComponent();
}
private void Interface_Load(object sender, EventArgs e)
{
PopulateList();
}
private void PopulateList()
{
int size = getTimes.Length;
lstTime.Items.Clear();
GetTimes();
for (int i = 0; i < size; i++)
{
lstTime.Items.Add(getTimes[i]);
}
}
private void GetTimes()
{
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
private void btnAdd_Click(object sender, EventArgs e)
{
string time = pickerTimeStart.Value.Hour.ToString() + pickerTimeStart.Value.Minute.ToString() + pickerTimeEnd.Value.Hour.ToString() + pickerTimeEnd.Value.Minute.ToString();
System.IO.File.AppendAllText(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt", time + Environment.NewLine);
PopulateList();
MessageBox.Show("Time added", "Ok");
//PopulateList();
}
}
}

As currently written, GetTimes does nothing except read the file:
private void GetTimes()
{
// "string[]" here overrides the outer scope
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
If you change it to this, it becomes more useful:
private string[] GetTimes()
{
return File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
... and then PopulateList can simply become:
lstTime.Items.Clear(); //so you aren't getting a bunch of dupes
lstTime.Items.AddRange(GetTimes().Select(t => new ListViewItem(t)).ToArray());
You can also remove this line because you don't need to keep a copy of the data in the class:
private string[] getTimes = ...
Note: If you decide to keep the data source local and not work solely against the file, much of this would change.

Related

How do I convert Morse code to ASCII text

Yes this is homework but I have spent a few hours trying to figure it out. So right now I am doing a project in which you convert plain text into morse code, I was able to do so and it was relatively easy. However, now I need to convert the morse code back into text and I've run into a roadblock. I am not sure if I should make a new dictionary and reverse the text and char or if I should just reverse the existing dictionary that I have already made. Also we're not allowed to use if or case statements which makes it a bit harder but not by too much.
Here is what I have so far:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Morse_Code_Converter
{
public partial class Form1 : Form
{
private Dictionary<char, String> morse = new Dictionary<char, String>()
{
{' ', " /" },{',', " --..--" }, {'.', " .-.-.-" }, {'?'," ..--.."},{'0'," -----"},{'1', " .----"},
{'2'," ..---"},{'3'," ...--"},{'4'," ....-"},{'5'," ....."},{'6'," -...."},{'7'," --..."},{'8'," ---.."},
{'9'," ----." },{'a', " .-"}, {'b', " -..."},{'c'," -.-."},{'d'," -.."},{'e'," ."},{'f'," ..-."},
{'g'," --."},{'h'," ...."},{'i'," .."},{'j'," .---"},{'k'," -.-"},{'l'," .-.."},{'m'," --"},{'n'," -."},
{'o'," ---"},{'p'," .--."},{'q'," --.-"},{'r'," .-."},{'s'," ..."},{'t'," -"},{'u'," ..-"},{'v'," ...-"},{'w'," .--"},
{'x'," -..-"},{'y'," -.--"},{'z'," --.."}
};
public Form1()
{
InitializeComponent();
}
private void convertToMorseButton_Click(object sender, EventArgs e)
{
string input = morseTextBox.Text;
var sb = new StringBuilder();
for (int index = 0; index < input.Length; index++)
{
var t = input[index];
input = input.ToLower();
string morseValue;
morse.TryGetValue(t, out morseValue);
sb.Append(morseValue);
}
textToMorseLabel.Text = sb.ToString();
}
private void morseToTextButton_Click(object sender, EventArgs e)
{
//This is where I want to convert
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void clearButton_Click(object sender, EventArgs e)
{
morseTextBox.Text = "";
}
private void morseClearButton_Click(object sender, EventArgs e)
{
textBox.Text = "";
}
}
}
If someone can help guide me in the right direction that would greatly appreciated.
Since this is a school project, I don't give you the code, but I will try to explain, how you can do it.
I suppose morse codes (in input) are separated by a space, so first use String.Split(' ') to get a string[] each with a morsecode string.
I also assume, that you're not familiar with 'Linq' (yet) - or are not allowed to use it, so now you iterate (with a for loop) through this array, then use a for loop to find the item in morses Dictionary that has the value equal to this morsecode and return the key.
Using this method you don't need an extra dictionary. However, if this was real code, you should create a reverse Dictionary, which is faster than this approach.

C# How to increase value in every second and the increment value is based on amount.text file

The IDE is Visual Studio 2010.
I have two text file called total-cost.txt and amount.txt
The file inside look like below:
total-cost.txt
4500000
amount.txt
600
The first text file (total-cost.txt) represents the total cost which will display at textbox(textbox name is totalcost).
A second file (amount.txt) represents the increment value for every second.
I'm trying to display the total of cost from total-cost.txt and auto increase the value in every second that set in the amount.txt
For example:
4500000 after 1 second become 4500600 after 2 second 4501200 and so on.
If I change the amount.txt value from 600 to 700 it become
4500000 after 1 second become 4500700 after 2 second 4501400 and so on.
The value will keep it refresh and display latest total cost only.
The issue is that I already display the total-cost value in textbox but I do not know how to increment a value that set by amount.txt
The coding I have done is in below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
namespace new_countdown
{
public partial class Form1 : Form
{
private string TotalCost;
private int TotalFont;
public Form1()
{
InitializeComponent();
}
private void ReadTotalCostFile()
{
try
{
StreamReader sr = File.OpenText("total-cost.txt");
TotalCost = sr.ReadToEnd();
sr.Close();
}
catch { }
}
private void UpdateDisplay()
{
if (totalcost.Text != TotalCost)
{
totalcost.Text = TotalCost;
}
if (totalcost.Font.Size != TotalFont && TotalFont != 0)
{
this.totalcost.Font = new System.Drawing.Font("Microsoft Sans Serif",(float)TotalFont,System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point,((byte)(0)));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateDisplay();
ReadTotalCostFile();
}
}
}
Somehow, I just have done the display total cost in the textbox.
I have no ideas to do for auto-increment.
Have anyone share the idea or solution. I have much appreciated it.
using System;
using System.IO;
private void IncrementInt32ValueInFile(string filePath)
{
var currentFileText = File.ReadAllText(filePath);
if (int.TryParse(currentFileText, out int integerValue))
{
File.WriteAllText(filePath, Convert.ToString(++integerValue));
}
throw new Exception($"Incorrect file content. Path: {filePath}"); // If value in file can't be parsed as integer
}

Trying to understand C#, WPF and User Input between functions

I am new here as well as to C#. I'm trying to learn it better and as a basic programming challenge for myself, I'm trying to understand how to move or return certain values from user input/text boxes after being submitted to a table that is displayed in a list.
Here is my "challenge" I'm trying to create a simple program that has 2 text boxes one for a name of the new value to a list (not an array I've learned that the hard way) and one for a name of a searched value in a said list. Submit button for each of those text boxes with a message stating either "Value Added" when it was added, or "Found" "Doesn't Exist" for the search button. Then on a side of said boxes and buttons I actually want to display my list with a scrollable 2 column window / box, First column as position in a table like value in which its at and then the actual name of the said value that was added. (Oh an also a clear button for the list itself)
So here is what I've gathered so far. I understand I have to transform all input into a string and then push it to the list. I know how to display the MessageBox.Show("") however I don't know how to code conditions to it. I would try a simple if () but I would first need to be able to program a working search function which requires pushing and pulling data from the list. I know JavaScript has array.push and array.indexof which makes finding and pushing things into an array rather simple, but to my knowledge, C# does not have that function.
I am new to this so any tips on a material to read that would help me learn C# or any tips on how to make this work properly will be appreciated. My biggest struggle is to return a value from the said text box into another private void and using it in my var, in other words pushing the product of a function into another function (like in the example below pushing the Add_Text.Text into the var names = new List<string>(); which is in another void above it. Anyway here is my coding or failed attempt at making this somewhat "work".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ArrayApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// ARRAY CODING / LIST CODING
public class Values
{
public string Position { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
public void App()
{
var names = new List<string>();
}
// BUTTON CLICKS / BUTTON ACTION CODING
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
Add_Text.Clear();
}
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
}
// TEXT BOXES / WHAT BUTTON ACTUALLY INPUTS INTO OUR DISPLAY
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
// DISPLAY - List_Box not added yet
}
}
Let's walk through this. As you've already mentioned, you need something to store your data. List is a good idea since you don't know the size.
Currently, you're creating a List of the type string, that would work.
There's actually no need for the Values class because because you can get the index of an item with a function called IndexOf - but later more.
Now, once you show the MessageBox when adding an item, you also have to actually add it to your names list. In order to do so, declare the List in your class and initialize it in your constructor. That way you're able to access if from everywhere in your class.
private List<string> names;
public void MainWindow()
{
InitializeComponent();
names = new List<string>();
}
Adding items can be done with the .Add method, it's pretty straight forward.
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
names.Add(Add_Text.Text); // Adding the content of Add_text.Text
Add_Text.Clear();
}
Searching for an item is pretty easy, too. Just use Contains if you want to know whether the item exists or IndexOf if you want to have the index as well. Note: IndexOf returns -1 if nothing can be found.
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if(names.Contains( SEARCH_TEXT.TEXT /* or wherever you get your pattern from */ )){
// found, display this in some way
} else {
// not found, display this is some way
}
}
SEARCH_TEXT.TEXT contains the pattern you're looking for. I don't know how you named your control, simply replace it.
That's pretty much it.
So, after doing some reading and also your comments helped a lot, I think I got hang of it and got some basic understanding of C# at least how it works logically. This is the "final" version of the AMAZING program I was trying to create. Thanks for the help everyone!
P.S. The comments are for me to learn and reference in the future when I'm learning C# or forget things :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
/* QUICK TERMINOLOGY
List = An Array that constantly adjusts its maximum size
names = Our actual "database" or table with our values that we've inputted
List_Box = The display table that is visible on the program itself
var = Variable... You know...
"public" or "private" = Those define whether the function is visible to the rest of the program or other "sheets" in the program
void = Defines whether the return value or the output of a function should be something, void means not specified,
if you want string you put string, if you want an integer you put int... etc etc.
*/
namespace ArrayApp
{
public partial class MainWindow : Window
{
/* Private Function for Creating the List which will be a String
We are using a List instead of an Array as an Array needs
a specific amount of indexes so if we have a specific number of data or
a maximum amount of data that a user can input then array would be used
but since we don't know how many indexes we need a list will automatically
adjust the maximum size of our table to suit our needs. I.e. limitless */
private List<string> names;
public MainWindow()
{
InitializeComponent();
names = new List<string>();
}
/* Class for our Items in our list this is not referring the list above but...
the list that it displays as we have a search on demand
but also allows us to search for specific people in the List (array/table) rather than
display over 100+ people, if our database was to get to that size.
Our class function defines what data can be put into our Display List ( List_Box )
Therefore the index can only be an integer and name can only be a string
more on this later. */
class Items
{
public int Index { get; set; }
public string Name { get; set; }
}
/* The Add Button Function
This button takes the content of the TextBox that is right next to it and
adds it to our list called "names" but does not update our display, instead
it shows us a message stating that the value was added to the list.
If we were using an Array with a limited size, we could use an IF to check
if there is a space available and output a message saying "Full" or "Failed" */
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
names.Add(Add_Text.Text); // Adds the value
Add_Text.Clear(); // Clears the text box
MessageBox.Show("Value Added"); // Displays a message
}
/* Firstly...
* We have an IF function that checks whether "names" contains the content
of the search box, so if its a letter "a", it checks if its in our list.
* It then creates a variable "SearchText" that we can later use that simply
means that instead of writing the whole code we can just refer to it by our new name
* Another variable! This one defines our Index in our list, it takes
our previous variable and looks for it in our list and finds what
the index number of that value is.
* Now, since its Search on demand we essentially have two Lists (arrays) now
that we have the name of the value we looking for in string format,
we also have our index as integer (defined earlier in class). We need to take that data
and add it to our display List and for that we have our function.
Adds new Items to our list using the Items Class and also defines
what data should be put into each column.
* It then clears the search text box
* and shows us that the value has been found.
We then move to ELSE which is simple really...
* Didn't find data
* Clears search text box
* Displays message that its not been found... */
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if (names.Contains(Search_Text.Text)) // Our If statement
{
var SearchText = Search_Text.Text; // First Variable
var FindIndex = names.IndexOf(SearchText); // Second Variable
List_Box.Items.Add(new Items() { Index = FindIndex, Name = SearchText}); // Adding items to display list
Search_Text.Clear(); // Clear search text box
MessageBox.Show("Data Found"); // Display message
}
else
{
Search_Text.Clear();
MessageBox.Show("Not Found");
};
}
/* Lastly a simple clear button for our display list.
* Once a user searches for many values and wants to clear the display list
* he can do it by hitting a single button.
*
* This button DOES NOT delete anything from our "names" list it only
* clears the display data meaning that the user can search for more data
* that has been added already. */
private void Clear_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Items.Clear();
}
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Here is how it looks, simple but you get the idea, I'm learning...

Greatest Value in a Dataset

I am attempting to find the greatest value in the highlighted column of this access database. I have tried a few ways of doing it but none of them work.
I need to use LINQ. Preferably the from x in y [...] select x; statement. If I cannot to this with the aforementioned then anything using LINQ would probably suffice. If you could explain why your answer works that would help me out a lot.
Edit:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CarStatistics
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'honestRalphsUsedCarsDataSet.tblCars' table. You can move, or remove it, as needed.
this.tblCarsTableAdapter.Fill(this.honestRalphsUsedCarsDataSet.tblCars);
}
private void btnCarAmount_Click(object sender, EventArgs e)
{
lblCarAmount.Text = "Our inventory consists of " + (dgvCars.RowCount - 1).ToString() + " cars!";
lblCarAmount.Visible = true;
}
private void btnMstExpensive_Click(object sender, EventArgs e)
{
//Code to find Max
}
}
}
The appropriate linq method to use would be [Enumerable.Max][1]. There are many overloads but the ones you will want are either the one that works on an IEnumerable<decimal> (assuming that that type of your column is decimal). This would be used as:
source.Select(x=>x.Price).Max()
source would be the IEnumerable that you have the data in and x.Price assumes that the value of that column is obtainable through a property called Price.
The other alternative would be using the overload of max that takes a Func<TSource, decimal> to tell it what data to use for the max:
source.Max(x=>x.Price)
I'm not sure there is much difference apart from in readability. I'd probably be inclined towards the first, particularly since in the first draft of this question I got wrong what the second actually returns (Thanks to Robert McKee for correcting me on that). :)
Something like this should be what you're looking for:
var maxPrice = db.Items.OrderByDescending(i => i.Value).FirstOrDefault().Value;
This works by ordering all of the rows based on the column specified, then takes the first row from that list, and selects the value of that column.

How would I be able to use the && operator in string types in C# (Speech Recognition)

I am writing my own speech recognition program in C# with Microsoft's engine and the way I have the program to recognise commands is to read what is already in a text file. The problem with this is, I have to say the command exactly as it is written. For example, if the command is "what is tomorrows date", I cannot say "what's tomorrows date". I have thought of way to get around it and that is to use the Contains method. Here is my code below,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.IO;
namespace TestDECA
{
public partial class Form1 : Form
{
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
SpeechSynthesizer DECA = new SpeechSynthesizer();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"D:\Luke's Documents\Speech Commands\TestCommands.txt")))));
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recongizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void _recongizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string speech = e.Result.Text;
if (speech.Contains("open" && "fire fox"))
{
System.Diagnostics.Process.Start(#"D:\Program Files (x86)\Mozilla Firefox\firefox.exe");
}
}
}
}
As you can see, I want to check if speech contains the words "open" and "fire fox". However, Visual Studio gives me an error saying that the && operator cannot be applied to strings. Is there a way of checking the text to see if contains those words or not? Any help at all will be appreciated.
The String.Contains() method takes a single string. "open" && "fire fox" does not evaluate to a string. If you want to check if a string contains two different values, do this:
if (speech.Contains("open") && speech.Contains("fire fox"))
{
...
}
You could create an extension method to help make this easier:
public static bool ContainsAll(this string str, params string[] values)
{
foreach (var value in values)
{
if (!str.Contains(value)) return false;
}
return true;
}
And then use it like this:
if (speech.ContainsAll("open", "fire fox"))
{
...
}

Categories