How to get user input in windows forms with array - c#

I am coding in C# and I am trying to use windows forms. I want to do a code where it gets the coordinates from a user 10 times and puts it in a stack.
Stack mystack =new stack();
For(X=0,X>6,X++)
{
Int row = 0
Int column=0
Console.Writeline("enter your row");
row=Console.Readline();
Console.Writeline("Enter your column");
column=Console.Readline()
mystack.Push(row,column);
The problem is that when I try to implement console.readline and writeline in windows forms it doesn't do anything when I use it. So I'm wondering if there is a tool I can use or a way to implement this.

You can build a few types of applications with C#; two of them are Console Applications and Windows Forms Applications.
Console Applications are just like the cmd, but with your code running in it. Therefore you can use the Console.Write, Console.WriteLine, and Console.Readline functions.
Windows Forms Application is a different kind of app that supports GUI. You can add buttons, text boxes, images, and more to build a graphical user interface where the user can interact with your application. In a Windows Forms Application you can't use the Console functions, as the console isn't available for the user.
I suggest adding two text boxes and a button to accomplish the task you want with a Windows Forms App.
TextBox 1: Row
TextBox 2: Column
Button: Pushes both values into the stack.
You can learn more about Windows Forms by looking into the official tutorial on Microsoft's website.

1. right click on windows form project. in the application section put output type to the console Application:
2. use this code:
Stack mystack = new Stack();
for (int x = 0; x < 10; x++)
{
int row = 0;
int column = 0;
Console.WriteLine("enter your row");
row = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your column");
column = int.Parse(Console.ReadLine());
mystack.Push(new object[] { row, column });
}

Your question is how to get user input in Windows Forms to populate a data structure that your code shows as an Stack. The way you would go about this in Winforms is very different from how you would do it in a Console application because UI programming is event driven.
You can use the designer to populate your main Form (for example) with labels, textboxes (in this case NumericUpDown) and buttons. The code behind the UI responds to events that happen when keys are pressed or buttons are clicked.
I hope this minimal code example can get you started:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
buttonAdd.Click += onAdd;
buttonContinue.Enabled = false;
}
Stack<Point> _myStack = new Stack<Point>();
private void onAdd(object? sender, EventArgs e)
{
_myStack.Push(
new Point(
int.Parse(numericTextBoxColumn.Text),
int.Parse(numericTextBoxRow.Text))
);
buttonAdd.Enabled = _myStack.Count < 10;
buttonContinue.Enabled = !buttonAdd.Enabled;
textBoxMultiline.Text =
string.Join(
Environment.NewLine,
_myStack.Select(_ => $"Col {_.X} Row {_.Y}").ToArray());
}
}

Related

When I open the second form within the first one, it doesn't work properly (C#)

I have two forms in my project (a simple game for kids). The first one is the start menu and the second one is the game. Now, when I click on New Game, I want the second form to open within the first one. I did that by using the following code:
private Form activeForm = null;
private void openChildForm(Form childForm1)
{
if (activeForm!=null)
{
activeForm.Close();
}
activeForm = childForm1;
childForm1.TopLevel = false;
childForm1.FormBorderStyle = FormBorderStyle.None;
childForm1.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm1);
panel1.Tag = childForm1;
childForm1.BringToFront();
childForm1.Show();
}
Now the second form opens within the first one, but it doesn't work properly. In my second form I have a picturebox, which is supposed to move when the user presses on one of the arrow keys. But it won't move.
Any suggestions what should I do?
P.S.
I'm a beginner and this is a school project. My teacher showed us only one way of opening a form:
Form2 objForm2 = new Form2();
objForm2.Show();
but since it is a very ugly method of getting the job done, I wanted to do it better.
I'm using Visual Studio 2019
I would suggest you to use a so called UserControl it's basically that what the name says: It's a custom windows forms control, witch has it's own child controls -> Just Like a form.

Have Winform appear on all existing monitors at same time (Its an alert window) [duplicate]

This question already has an answer here:
Have winforms MessageBox appear on all screens, or specify Main or Secondary etc.
(1 answer)
Closed 8 years ago.
I have a small application which functions as an alert system, I am using a form as the alert which appears on the screen, as they are more versatile and message boxes. Due to the nature of the alert, I need it to appear in the centre of all currently connected monitors.I have it appearing on hte main monitor only as of right now.
I've looked at these 2 posts on here:
Showing a Windows form on a secondary monitor?
How do I ensure a form displays on the "additional" monitor in a dual monitor scenario?
But I really can't get my head around it, I've looked into the Screens.AllScreens property, but still feel no better at understanding how to tell the form which monitor to appear on, and even further from having it appear on multiple, as I'm assuming I'd need to foreach loop through AllScreens array.
I'd also need to close all the forms from a button clock on one of them, but right now I just want to have them on all monitors.
Sorry to ask a question I feel most people consider already answered.
This one worked perfectly for me..
First create an alert form with a label inside.
set the label1 property -> Modifier = public
void showMsgOnAllScreens(string msg)
{
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
AlertForm alert = new AlertForm();
alert.label1.Text = msg;
alert.StartPosition = FormStartPosition.Manual;
alert.Location = new Point(
Screen.AllScreens[i].Bounds.Left + (Screen.AllScreens[i].Bounds.Width / 2 - alert.Width / 2),
Screen.AllScreens[i].Bounds.Height / 2 - alert.Height / 2);
alert.Show();
}
}
.
.
.
Now simply call the method to show msgs on all screens..
void button1_click (object sender, EventArgs e)
{
showMsgOnAllScreens("Warning.. Something's burning..!!");
}

Creating Multiple Form GUI

I am developing a very basic application Windows Form Application in c# that inserts values into a SQL database.
I have four separate forms
one for inputting customer details
one for inputting any transaction details
one for searching customers/transactions respectively.
What is the best way link all four forms together? I'm only just getting into C# so the most basic way possible would be ideal.
The way I see it working in my head is that you run the program and end up on one screen which shows four buttons for the four corresponding forms. When you press the button a separate window opens showing the insert forms. You can then close the form to return to the Main Start Screen
What would be the basic code for this in C#? For examples sake lets say the 5 different layouts are
Main (Containing the buttons)
TransactionEntry
AddressEntry
TransactionSearch
AddressSearch
Okay, here is an example of how I would do it. On the main form on button click event:
frmSecondForm secondForm = new frmSecondForm(this); //"this" is passing the main form to the second form to be able to control the main form...
secondForm.Show();
this.Hide();
One your Second Forms constructor code:
Form frmHome;
frmSecondForm(Form callingForm) //requires a calling form to control from this form
{
Initialize(); //Already here
frmHome = callingForm as frmMain;
}
Then on the second form's closing unhide the main form:
frmSecondForm_FormClosing()
{
frmHome.Show();
}
So all in all, if you needed to pass data between the forms just add it as a parameter on the second form.
Again, I would consider placing your data collection into a repository package (folder) and class, then create a User.cs class that will hold all of the information you keep in the database.
Hint: Right click your top level item in solution explorer and go to New -> Folder. Name it Repo.
Right click that folder and go to New -> Class and name it UserRepo.
In here build functions to collect the data from the databases.
On your main form's constructor area, call the class (repo).
private Repo.UserRepo userRepo;
frmMain_FormLoad()
{
userRepo = new Repo.UserRepo();
}
Then on log in button click:
private button1_ClickEvent()
{
if(userRepo.isValidLogin(userNameText, passwordText))
{
//Do stuff
}
}
for userRepo.isValidLogin()
public bool isValidLogin(String username, String password)
{
bool isValid = false;
//Write up data code
return isValid;
}
From the Main form use eg:
TransactionEntry trans = new TransactionEntry();
trans.ShowDialog();
.ShowDialog() will show the new form, but will halt any code executing on the Main form until you close it
(This assumes your forms are all in the same solution)
You could try the MDI (Multiple Document Interface) way, here is a nice tutorial: http://www.dreamincode.net/forums/topic/57601-using-mdi-in-c%23/

How to show non-interactive, auto-hiding notification popup message with Windows Forms in c#?

Using Windows Forms, .NET 3.5 framework, language: c#
I would like to show a popup window for 1 second to notify users of actions that are performed. For example, when I copy a file X I want to show a notification like "Copied file X to File X-copy". Should be shown for a second, then autohide.
You can use a timer. Something along the lines of the following where ShowFloating does the initial display and HideFloating does, you know.
public void ShowFloatingForXMilliSeconds(int milliSeconds) {
ShowFloating();
if (_autoOffTimer == null) {
_autoOffTimer = new System.Timers.Timer();
_autoOffTimer.Elapsed += OnAutoOffTimerElapsed;
_autoOffTimer.SynchronizingObject = this;
}
_autoOffTimer.Interval = milliSeconds;
_autoOffTimer.Enabled = true;
}
void OnAutoOffTimerElapsed(Object sender, System.Timers.ElapsedEventArgs ea) {
if ((_autoOffTimer != null) && _autoOffTimer.Enabled) {
_autoOffTimer.Enabled = false;
HideFloating();
}
}
Also detach the timer handler and dispose the timer in Dispose.
This topic will help you to make topmost window without stealing focus from currently active window.
To complete your solution, in simple case you need to add a timer on your form to make sure the form auto-closes after 1 second and locate your notification window properly (you probably want it in the bottom right part of the screen? - that's a simple arithmetic exercise).
For more advanced solution, you should create NotificationManager class and manage lifetime of your notification message forms there.
Dispite the answers given. I think a message that pops up is somewhat not user friendly. What about using a statusbar link? It's not that evasive (and you can show the progress)

Top level window in WinForms

There are a lot of questions around about this for WinForms but I haven't seen one that mentions the following scenario.
I have three forms:
(X) Main
(Y) Basket for drag and drop that needs to be on top
(Z) Some other dialog form
X is the main form running the message loop.
X holds a reference to Y and calls it's Show() method on load.
X then calls Z.ShowDialog(Z).
Now Y is no longer accessible until Z is closed.
I can somewhat understand why (not really). Is there a way to keep Y floating since the end user needs to interact with it independently of any other application forms.
If you want to show a window using ShowDialog but you don't want it block other windows other than main form, you can open other windows in separate threads. For example:
private void ShowY_Click(object sender, EventArgs e)
{
//It doesn't block any form in main UI thread
//If you also need it to be always on top, set y.TopMost=true;
Task.Run(() =>
{
var y = new YForm();
y.TopMost = true;
y.ShowDialog();
});
}
private void ShowZ_Click(object sender, EventArgs e)
{
//It only blocks the forms of main UI thread
var z = new ZForm();
z.ShowDialog();
}
In x, you can put a y.TopMost = true; after Z.ShowDialog(). This will put y on the top. Then, if you want other forms to work, you can put a y.TopMost = false; right after the y.TopMost = true; This will put the window on top, but allow other forms to go over it later.
Or, if the issue is one form being put on top of the other, then you can change the start position of one of the forms in the form's properties.
You can change your main form (X) to be an MDI container form (IsMdiContainer = true). Then you can add the remaining forms as child forms to X. Then use the Show method instead of ShowDialog to load them. This way all child forms will float within the container.
You can add the child forms to X like this:
ChildForm Y = new ChildForm();
Y.MdiParent = this //X is the parent form
Y.Show();

Categories