How to modify and show a queue in a WPF c# - c#

I'm trying to show in a TextBox in a Windows Presentation Foundation a queue after adding some items, I know it must be something simple, I've checked the code with a breakpoint, the Add Item button works good but once I press it again the queue is empty and I'm always adding just an item and once I add it and I press the same button Add Item button again or the Show Button the queue is empty, I would like to add items and show the queue with the items I added, I made a class named QueueClas. Here below is all the code, thanks beforehand!!
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 Queue2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
QueueClas queuec = new QueueClas();
buttonAdd.Click += ButtonAdd_Click;
buttonShow.Click += ButtonShow_Click;
}
private void ButtonShow_Click(object sender, RoutedEventArgs e)
{
QueueClas queuec = new QueueClas();
textBoxShow.Text = queuec.ShowQueue();
}
private void ButtonAdd_Click(object sender, RoutedEventArgs e)
{
QueueClas queuec = new QueueClas();
queuec.AddQueue(int.Parse(textBoxQueue.Text));
textBoxQueue.Clear();
}
public class QueueClas
{
Queue<int> myqueue;
public QueueClas()
{
myqueue = new Queue<int> { };
}
public void AddQueue(int x)
{
myqueue.Enqueue(x);
}
public string ShowQueue()
{
return string.Join(" ", myqueue);
}
public void DeleteItem(int x)
{
myqueue.Dequeue();
}
public string NumberOfItems()
{
int counter = 0;
counter = myqueue.Count();
return "The queue contains " + counter.ToString() + " elements";
}
public string MinQueue()
{
return "The minimun value of the queue is: " + myqueue.Min().ToString();
}
public string MaxQueue()
{
return "The maximum value of the queue is: " + myqueue.Max().ToString();
}
public string FindElement(int x)
{
foreach (int item in myqueue)
{
if (x == item)
{
return "The item is in the queue";
}
}
return "The item is not in the queue";
}
}
}
}

In both the add and show buttons you are initialising your list with QueueClas queuec = new QueueClas();. This is completely erasing the list ans starting fresh. You already initialise it in your MainWindow constructor so there's no need to do it again.

Related

Run method from another class to scroll listbox to bottom

I want to autoscroll WPF ListBox to bottom automatically. I have two classes - one is Timer.cs and another one is MainWindow.xaml.cs
Here is Timer.cs:
using System;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Importer_WPF
{
class Timer
{
public static readonly string MinutesExecution = ConfigurationManager.AppSettings["MinutesExecution"];
static System.Threading.Timer timer;
public static void StartTimer()
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(MinutesExecution));
timer = new System.Threading.Timer((e) =>
{
Task.Delay(100).ContinueWith(_ => App.Current.Dispatcher.Invoke(() => MainWindow.Names.Add(DateTime.Now.ToString())));
MainWindow.AutoScroll(); // Problem is here
}, null, startTimeSpan, periodTimeSpan);
}
public static void StopTimer()
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
}
}
}
MainWindow.xaml.cs:
using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
namespace Importer_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static ObservableCollection<string> Names { get; set; }
public static bool IsCheckedYes { get; set; }
[Obsolete]
public MainWindow()
{
InitializeComponent();
}
public void AutoScroll()
{
int itemCount = ConsoleOutput.Items.Count - 1;
if (itemCount > -1)
ConsoleOutput.ScrollIntoView(ConsoleOutput.Items[itemCount]);
}
}
}
Debugger is giving this message:
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field,
method, or property 'MainWindow.AutoScroll()'
Any hints how to edit code structure so it will not produce errors?
You need to get a reference to the instance of mainwindow class which is in memory.
((MainWindow)Application.Current.MainWindow).AutoScroll();

Error when creating a Double linked List in a form

I am new to C#, and I am trying to create a step by step program that will create and display the nodes of a double linked list. I will show what I have so far:
This is the code for the form:
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 Pruebapila2
{
public partial class Form1 : Form
{
DbLinList infoTask;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
infoTask = new DbLinList();
}
private void button1_Click(object sender, EventArgs e)
{
taskToDo vInfo = new taskToDo(int.Parse(textBox1.Text), textBox4.Text, textBox2.Text, textBox5.Text, textBox3.Text);
infoTask.insertAtTheEnd(vInfo);
listBox1.Items.Add("Data Added: "+ vInfo.id + " - " + vInfo.name + " - " + vInfo.length + " - " + vInfo.percentage + " - " + vInfo.programmer);
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Node n;
n = infoTask.firstNode;
while (n != null)
{
listBox1.Items.Add(Convert.ToString(n.info.id) + "\t" + n.info.name + "\t" + n.info.length);
n = n.Next;
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
Node n;
n = infoTask.firstNode;
while (n != null)
{
if (n.info.id == int.Parse(textBox6.Text))
listBox1.Items.Add(Convert.ToString(n.info.id) + "\t" + n.info.name + "\t" + n.info.length);
n = n.Next;
}
}
}
}
When you click on the first button of the form, it will insert the data into a Node, the node belongs to a double linked list, therefore here is the code for the list.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pruebapila2
{
class DbLinList
{
public Node firstNode;
public DbLinList()
{
firstNode = null;
}
public DbLinList insertAtTheEnd(taskToDo vTaskToDo)
{
Node newNode;
newNode = new Node(vTaskToDo);
newNode.Next = firstNode;
newNode.Prev = firstNode.Next;
firstNode = newNode;
return this;
}
}
}
This list uses a Node that has a link to the previous node, and a link to the next node of the list. Here is the code for the Node:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pruebapila2
{
class Node
{
public taskToDo info;
public Node Next;
public Node Prev;
public Node(taskToDo vInfo)
{
info = vInfo;
Next = null;
Prev = null;
}
}
}
The node is reusable because it can contain any type of info, and even several parts of information, but in this case this node will contain information about a task that a programmer has to make, for that reason I created a tasks.cs file, which will contain the information that we need to store on the list. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pruebapila2
{
class taskToDo
{
public int id;
public string name;
public string length;
public string percentage;
public string programmer;
public taskToDo(int vID, String vName, String vLength, String vPercentage, String vProgrammer)
{
id = vID;
name = vName;
length = vLength;
percentage = vPercentage;
programmer = vProgrammer;
}
}
}
The code shows no errors and no warnings, when executed, it displays the ERROR: "An unhandled exception of type 'System.NullReferenceException' occurred in DoubleLinkedTest.exe." But I have no clue as to why is this error appearing.
The logic here is the following: The button sends the data to the list, the list creates a new node, the node creates a new task, and the info is stored in the node.
Can anyone tell me what is wrong with the code, why is not working?. The functions of the button number 2 and 3 are not in question at the moment.
This is how the form looks like:
Thank you very much for your Help on this!.

C#: Dynamicly Add Items to Scrollview Control in WPF Application

Currently I am trying to code a WPF application that will store books and users for an imaginary library(I need to prove someone wrong). In my code, I have a class for Books and one for users. Inside of each will be a static list that keeps track of them all. What I would like to do is list out all the books and users so the viewer can see them. I thought I could do this with a scrollview and add labels to it that store the information(This would be in a separate window than the main screen, you would get there by pressing a button). However, I have been having some trouble with this.
LibraryCore:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LibraryCore
{
class User
{
}
class Books
{
public static List<Books> bookslist = new List<Books>();
public static void NewBook(string _title, string _author, string _publisher, int _isbn, int _count = 1)
{
bookslist.Add(new Books(_title, _author, _publisher, _isbn, _count));
}
public static void AddBook(string _title, int _amount)
{
bookslist[bookslist.FindIndex(b => b.Title.ToUpper() == _title.ToUpper())].Count += _amount;
}
public List<Books> currentLoans = new List<Books>();
public string Publisher { get; private set; }
public string Author { get; private set; }
public string Title { get; private set; }
public int ISBN { get; private set; }
public int Count { get; private set; }
Books(string _title, string _author, string _publisher, int _isbn, int _count = 1)
{
Title = _title;
Author = _author;
Publisher = _publisher;
ISBN = _isbn;
Count = _count;
}
}
}
MainWindow:
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;
using LibraryCore;
namespace LibraryLikeWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnNewBook_Click(object sender, RoutedEventArgs e)
{
Books.NewBook("Odessy", "SOME OLD GUY", "Athens Inc.", 0);
//Books.NewBook("OLD YELLER", "SOME OLD GUY", "Athens Inc.", 2);
//Books.NewBook("This old man", "SOME OLD GUY", "Athens Inc.", 1);
}
private void btnInfo_Click(object sender, RoutedEventArgs e)
{
BookList bookList = new BookList();
bookList.Show();
}
}
}
BookListWindow:
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.Shapes;
using LibraryCore;
namespace LibraryLikeWpf
{
/// <summary>
/// Interaction logic for BookList.xaml
/// </summary>
public partial class BookList : Window
{
public BookList()
{
InitializeComponent();
for(int b = 0; b < Books.bookslist.Count; b++)
{
Label lbl = new Label();
lbl.VerticalAlignment = VerticalAlignment.Top;
lbl.Content = String.Format("Title: {0} Author: {1} Publisher: {2} ISBN: {3}",Books.bookslist[b].Title,Books.bookslist[b].Author, Books.bookslist[b].Publisher, Books.bookslist[b].ISBN);
lbl.Width = 100000;
scrollGrid.Children.Add(lbl);
}
}
}
}
This code works, but if I add several Books, the BookListWindow will just overlap the labels and I would like to know how to change their position when they are instantiated. Also, the labels get cut off even though their width shouldn't inhibit that. Why does that happen and how can I fix it? Also, is there a better way to list out ALL of the items in a list in a better looking way?
If your are using XAML, try to use ListView with Binding.
Create a ObservableCollection of Books and bind this to your ListView, this way you can control show your items are shown.

Windows form loads then quits

I'm creating a checkout system for a supermarket. It consists of a checkout, server and MIS program an operates WCF services between them. The problem I have is that the checkout program, which is a windows form, does a few neccessaries in it's application_load method and then just quits.
Here's the code:
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 CheckoutLibrary;
using Checkout.ServerLibraryService;
using Checkout.MarketService;
namespace Checkout
{
public partial class theForm : Form
{
private static int checkoutID = 3;
private Product[] allProducts;
public theForm()
{
InitializeComponent();
}
private void theForm_Load(object sender, EventArgs e)
{
// First cache all products
SupermarketServiceSoapClient marketService = new SupermarketServiceSoapClient();
allProducts = marketService.GetAllProducts();
// Load the service provided by the server
ServiceClient serverService = new ServiceClient();
// Load the event handlers for the bar code scanner
BarcodeScanner scanner = new BarcodeScanner();
scanner.ItemScanned += new BarcodeScanner.ItemScannedHandler(scanner_ItemScanned);
scanner.AllItemsScanned += new BarcodeScanner.AllItemsScannedHandler(scanner_AllItemsScanned);
scanner.Start(checkoutID);
}
void scanner_AllItemsScanned(EventArgs args)
{
throw new NotImplementedException();
}
void scanner_ItemScanned(ScanEventArgs args)
{
itemTextBox.Text = "Scanned " + GetItemName(args.Barcode);
}
private void scanItemButton_Click(object sender, EventArgs e)
{
scanner_ItemScanned(new ScanEventArgs(GetRandBarcode()));
}
// A barcode -> product name look up method
public string GetItemName(int barcode)
{
return allProducts[barcode].Description + " # " + allProducts[barcode].Price;
}
// Method to grab a random barcode for simulation
private int GetRandBarcode()
{
Random rand = new Random();
return rand.Next(0,500);
}
}
}
And program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Checkout
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new theForm());
}
}
}
Thanks for any insight.
In WinForms, if your form_load throws an exception, it quits without displaying anything. Annoying, but I'm guessing that's the problem.
You can try a try/catch, or you can hit CTRL+ALT+E and check the Thrown Column for Common Language Runtime Exceptions to see the error.
UPDATE:
Based on comments, here's a sample way to execute something on another thread.
ThreadStart ts = new ThreadStart(() => {
try {
scanner.Start(checkoutID);
} catch {
// Log error
}
});
Thread t = new Thread(ts);
t.Start();

Simple C# WPF form generating a slew of seemingly nonsensical error messages

The code below contains a "whole bunch" of error messages, and I can't for the life of me figure out why. I recently had to "downgrade" from VS2010 to VS2008, and have had nothing but misery since. The first few error messages are shown as comments next to where they are occurring.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.IO;
namespace UniClient_NextGen
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void buttonPopMenuItemsLU_Click(object sender, RoutedEventArgs e)
{ // err msg #1 = "} expected"
public static int TOPLEVEL_ID = 0;
public static int PARENT_ID = 1;
public static int SELF_ID = 2;
public static int MENU_CAPTION = 3;
public static int MENU_NAME = 4;
string fileName = #"C:\_UniClientNextGen\MenuItemsWithIDs.txt";
using (StreamReader reader = File.OpenText(fileName)) // err msg #2 = "Invalid token 'using' in class, struct, or interface member declaration" + err msg #3 = "; expected" (at end of this line)
{
string _line = null;
string[] strElements;
do
{
_line = reader.ReadLine();
strElements = _line.Split(",");
// strElements should now have five elements
int iTopLevelID = Convert.ToInt32(strElements[TOPLEVEL_ID]);
int iParentID = Convert.ToInt32(strElements[PARENT_ID]);
int iOwnID = Convert.ToInt32(strElements[SELF_ID]);
string sMenuCaption = strElements[MENU_CAPTION];
string sMenuName = strElements[MENU_NAME];
//performSQL("INSERT INTO MENU_ITEMS_LOOKUP (TopLevelMenuID, ParentMenuID, MenuItemName, MenuItemCaption) VALUES (iTopLevelID, iParentID, iOwnID, sMenuCaption, sMenuName)");
} while (_line != null);
}
} // err msg #4 = "Type or namespace definition, or end-of-file expected"
private void buttonPopSorterTypesLU_Click(object sender, RoutedEventArgs e)
{
//
}
private void buttonPopTabsheetsLU_Click(object sender, RoutedEventArgs e)
{
//
}
private void buttonPopMenuItem_SorterTypeM2M_Click(object sender, RoutedEventArgs e)
{
//
}
private void buttonPopSorterType_TabsheetM2M_Click(object sender, RoutedEventArgs e)
{
//
}
}
}
Why do you have public static declarations inside of a method?
Here is the corrected code (I have moved static member declaration in right place and corrected the _line.Splt() parameter):
//...
public static int TOPLEVEL_ID = 0;
public static int PARENT_ID = 1;
public static int SELF_ID = 2;
public static int MENU_CAPTION = 3;
public static int MENU_NAME = 4;
void buttonPopMenuItemsLU_Click(object sender, RoutedEventArgs e) {
string fileName = #"C:\_UniClientNextGen\MenuItemsWithIDs.txt";
using(StreamReader reader = File.OpenText(fileName)) {
string _line = null;
string[] strElements;
do {
_line = reader.ReadLine();
strElements = _line.Split(',');
int iTopLevelID = Convert.ToInt32(strElements[TOPLEVEL_ID]);
int iParentID = Convert.ToInt32(strElements[PARENT_ID]);
int iOwnID = Convert.ToInt32(strElements[SELF_ID]);
string sMenuCaption = strElements[MENU_CAPTION];
string sMenuName = strElements[MENU_NAME];
} while(_line != null);
}
}
//...
I think you're XAML definition or XAML namespace is not in sync with your class. Did you recently rename a class or a namespace?

Categories

Resources