Message box in UWP not working - c#

Please help me, I have ran into a problem. I'm new in UWP coding
problem : I have build a simple application which consists of a button. When the button is pressed it will display a message
Error : Cannot find typre System.Collections.CollectionBase in module CommonLanguageRuntimeLibrary
Here is my code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Windows.MessageBox;
using System.Windows.Forms;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("HI");
}
}
}

There is no MessageBox in UWP but there is a MessageDialog:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using System;
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dialog = new MessageDialog("Hi!");
await dialog.ShowAsync();
}
}
}

I strongly recommend you to use a separate, function to display a popup message.
UWP uses the namespace Windows.UI.Popups and not System.Windows.MessageBox, since it's only used for Win32 or WinForms applications
Here's a good way to display your desired message:
// Other namespaces (essential)
...
// Required namespaces for this process
using Windows.UI.Popups;
using System.Runtime.InteropServices;
namespace PopupMessageApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
// I will only comment those that are not obvious to comprehend.
private async void ShowMessage(string title, string content, [Optional] object[][] buttons)
{
MessageDialog dialog = new MessageDialog(content, title);
// Sets the default cancel and default indexes to zero. (incase no buttons are passed)
dialog.CancelCommandIndex = 0;
dialog.DefaultCommandIndex = 0;
// If the optional buttons array is not empty or null.
if (buttons != null)
{
// If there's multiple buttons
if (buttons.Length > 1)
{
// Loops through the given buttons array
for (Int32 i = 0; i < buttons.Length; i++)
{
/* Assigns text and handler variables from the current index subarray.
* The first object at the currentindex should be a string and
* the second object should be a "UICommandInvokedHandler"
*/
string text = (string)buttons[i][0];
UICommandInvokedHandler handler = (UICommandInvokedHandler)buttons[i][1];
/* Checks whether both variables types actually are relevant and correct.
* If not, it will return and terminate this function and not display anything.
*/
if (handler.GetType().Equals(typeof(UICommandInvokedHandler)) &&
text.GetType().Equals(typeof(string)))
{
/* Creates a new "UICommand" instance which is required for
* adding multiple buttons.
*/
UICommand button = new UICommand(text, handler);
// Simply adds the newly created button to the dialog
dialog.Commands.Add(button);
}
else return;
}
}
else
{
// Already described
string text = (string)buttons[0][0];
UICommandInvokedHandler handler = (UICommandInvokedHandler)buttons[0][1];
// Already described
if (handler.GetType().Equals(typeof(UICommandInvokedHandler)) &&
text.GetType().Equals(typeof(string)))
{
// Already described
UICommand button = new UICommand(text, handler);
// Already described
dialog.Commands.Add(button);
}
else return;
}
/* Sets the default command index to the length of the button array.
* The first, colored button will become the default button or index.
*/
dialog.DefaultCommandIndex = (UInt32)buttons.Length;
}
await dialog.ShowAsync();
}
private async void MainPage_Load(object sender, EventArgs e)
{
/* Single object arrays with a string object and a "UICommandInvokedHandler" handler.
* The ShowMessage function will only use the first and second index of these arrays.
* Replace the "return" statement with a function or whatever you desire.
* (The "return" statement will just return and do nothing (obviously))
* (Edit: Changed 'e' to 'h' in UICommandInvokedHandler's)
*/
object[] button_one = { "Yes", new UICommandInvokedHandler((h) => { return; }) };
object[] button_two = { "No", new UICommandInvokedHandler((h) => { return; }) };
/* Object arrays within an object array.
* The first index in this array will become the first button in the following message.
* The first button will also get a different color and will become the default index.
* For instance, if you press on the "enter" key, it will press on the first button.
* You can add as many buttons as the "Windows.UI.Popups.MessageDialog" wants you to.
*/
object[][] buttons = new object[][]
{
button_one,
button_two
};
// Displays a popup message with multiple buttons
ShowMessage("Title", "Content here", buttons);
/* Displays a popup message without multiple buttons.
* The last argument of the ShowMessage function is optional.
* because of the definition of the namespace "System.Runtime.InteropServices".
*/
ShowMessage("Title", "Content here");
// PS, I have a life, just trying to get points xD // BluDay
}
}
}
This way, you can display a message dialog with or without passing an object array with subarrays that contains of buttons. This method is extremely efficient. If you like this, make sure you fully understand it!

Related

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...

No overload for method matches delegate?

I am new to c# and I am trying to learn Windows Phone development. What I am trying to do is simply be able to move a rectangle with your finger but I get this error:
Error 1 No overload for 'Drag_ManipulationDelta' matches delegate 'System.EventHandler<Windows.UI.Xaml.Input.ManipulationDeltaEventHandler>' C:\Users\Zach\documents\visual studio 2013\Projects\App2\App2\MainPage.xaml.cs 35 46 App2
I have seen this 'No overload for method matches delegate' question asked before but since I am new I am a little confused on what is going on.
Here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace App2
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private int buttonCount = 0;
private TranslateTransform dragTranslation; // For changing position of myRectangle
private SolidColorBrush redRect = new SolidColorBrush(Windows.UI.Colors.Red);
public MainPage()
{
this.InitializeComponent();
myRectangle.ManipulationDelta += new EventHandler<ManipulationStartedEventHandler>(Drag_ManipulationDelta);
//myRectangle.ManipulationDelta += new System.EventHandler<ManipulationDeltaEventArgs>(Drag_ManipulationDelta);
dragTranslation = new TranslateTransform();
myRectangle.RenderTransform = this.dragTranslation;
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
// < Called when myButton is pressed >
private void myButton_Click(object sender, RoutedEventArgs e)
{
buttonCount += 1;
myRectangle.Fill = redRect;
resultText.Text = "";
// Determines visibility of myRectangle
if(buttonCount % 2 != 0)
{
myRectangle.Visibility = Visibility.Visible;
}
else
{
myRectangle.Visibility = Visibility.Collapsed;
}
}
// < Called when myRectangle is pressed >
private void myRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
{
resultText.Text = "You touched the rectangle.";
}
void Drag_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
// Move the rectangle.
dragTranslation.X += e.Delta.Translation.X;
dragTranslation.Y += e.Delta.Translation.Y;
//dragTranslation.Y += e.DeltaManipulation.Translation.Y;
}
}
}
Thanks
Neither version of the event subscription you show in your post – the commented-out one, and especially the one before that (using an event handler delegate type itself as the type parameter for the EventHandler<T> type just makes no sense at all in any context) – use a type that is consistent with your actual method, hence the error.
The compiler complains that no overload matches, because it is theoretically possible to have multiple methods having the same name. So an error that simply says "the method" doesn't match wouldn't make sense. It is the case that none of the available methods with that name match; in this case, it just happens there's only one available method.
Without the declaration for the myRectangle object and its type, and in particular the ManipulationDelta event, it's not possible to know for sure what you need to do.
However, most likely you can just get rid of the explicit delegate type altogether:
myRectangle.ManipulationDelta += Drag_ManipulationDelta;
Then you don't need to guess as to what type to use for the delegate instance initialization. The compiler will infer the correct type and even the delegate instantiation on your behalf.
If that doesn't work, then you need to fix the method declaration so that it does match the event's delegate type. Without seeing the event declaration and its type, I can't offer any specific advice about that.
EDIT:
Per your explanation that you are trying to follow the example at Quickstart: Touch input for Windows Phone 8, I can see that your method declaration is incorrect.
The event is declared as EventHandler<ManipulationDeltaEventArgs>, but your method uses ManipulationDeltaRoutedEventArgs as the type for its second parameter. Why Microsoft chose to change the name between the older Phone API and the new XAML/WinRT API I don't know. But it's important to keep the right type:
void Drag_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
Note that my previous comment still applies as well; you don't need to specify the delegate type when subscribing. You can write the event subscription as I showed originally above.

Dynamic creation of forms & containers

I'm very new to C#.
Below is a code that I'm trying to create forms and containers within the code; but I've problems with it.
I start with a new Windows Forms Application template.
I change the Program.cs file a little, so that I'd be able to create the FormMain dynamically.
When the lines Container.Add(BtnClose) and BtnClose_Setup() in FormMain.cs are commented, the code compile and run. However, there are still some weird results in the program.
(a) The form FormMain is supposed to show up at (20, 20) (upper left corner), as the FormMain_Setup says; but when I run the app, though width & height settings show up as expected (800, 600), the upper left corner changes every time (does not stick to 20, 20).
(b) The esc key works as expected and closes the form and application.
When the lines Container.Add(BtnClose) and BtnClose_Setup() in FormMain.cs are not commented, the code compile but VS sends me a message when it's run: "An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll"
Can someone tell me what I'm doing wrong?
Program.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test {
static class Program {
public static FormMain FormMain = new FormMain();
[STAThread]
static void Main() {
Application.Run(FormMain);
}
}
}
FormMain.cs file:
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 test {
public partial class FormMain : Form {
Button BtnClose = new Button();
public void BtnClose_Setup() {
BtnClose.Text = "Ok";
BtnClose.Top = 500;
BtnClose.Left = 700;
}
public void FormMain_Setup() {
Top = 20;
Left = 20;
Width = 800;
Height = 600;
KeyDown += FormMain_KeyDown;
//Container.Add(BtnClose);
//BtnClose_Setup();
}
void FormMain_KeyDown(object sender, KeyEventArgs e) {
if(e.KeyCode == Keys.Escape) {
Close();
}
}
public FormMain() {
InitializeComponent();
FormMain_Setup();
}
}
}
Call Controls.Add(BtnClose); instead of Container.Add(BtnClose);.
As for fixing the form position: set StartPosition = FormStartPosition.Manual; property.
To properly close the form on Esc, override ProcessCmdKey method:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
By default a forms StartPosition is set to WindowsDefaultLocation. You need to set it to Manual; either in the designer or in the code.
To add a control to a form, you want to add it to the form's Controls collection, not the Container.
Also, if you want the form to continue to get KeyDown events after the button is added you need to set KeyPreview to true.
public void FormMain_Setup()
{
StartPosition = FormStartPosition.Manual;
KeyPreview = true;
Top = 20;
Left = 20;
Width = 800;
Height = 600;
KeyDown += FormMain_KeyDown;
Controls.Add(BtnClose);
BtnClose_Setup();
}

Listing integers from a text file into a listview

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.

Categories