In one of my current projects, I have been attempting to develop a system that will take data input from textboxes on one form, and input them into a list on another form so that they may be displayed via a listbox and labels on another form as a data reference for manual input into a database.
//Create Attendance Report Instance
AttendanceReport report = new AttendanceReport();
private void inputButton_Click(object sender, EventArgs e)
{
try
{
//Declare Variables
string administratorVerify = verificationBox.Text;
//Inputs Change Based on NewStudent Check
if (passwordInput.Text == passwordTextBox.Text)
{
//Save Changes
Save();
}
Relevant Section => else if (newStudentCheck.Checked == true)
{
//New Verification Instance
VerificationClass verify = new VerificationClass();
//Verification Gateway
if (verify.Verify(administratorVerify) == true)
{
//Send Student to Attendance Report List
report.DisplayStudent();
}
else
{
MessageBox.Show("Unauthorized Password\nOnly Authorized Administrators May Access this Function");
}
}
//Clear Inputs
clearInputs();
}
I designed the part of the program that retrieves the data and displays it to function off of an universal instance of the second form, calling an instance of the first form to retrieve the data. I originally had the program create a new instance of the second form whenever the input button was clicked, before I moved the instantiation out of that block, making it a universal instance.
List<NewStudent> studentList = new List<NewStudent>();
private void RetrieveStudentInfo(NewStudent student)
{
//Temp Variables
int ID;
int Grade;
//Create MainForm Instance
MainForm reference = new MainForm();
//Get Values
student.Class = reference.classBox.Text;
student.Name = reference.nameBox.Text;
if (int.TryParse(reference.idBox.Text, out ID))
{
student.ID = ID;
}
else
{
MessageBox.Show("Invalid ID");
}
student.Password = reference.createPasswordBox.Text;
student.District = reference.districtBox.Text;
student.Country = reference.countryBox.Text;
if (int.TryParse(reference.gradeBox.Text, out Grade))
{
student.Grade = Grade;
}
else
{
MessageBox.Show("Invalid Grade");
}
}
public void DisplayStudent()
{
//Create Object
NewStudent student = new NewStudent();
//Get Student Info
RetrieveStudentInfo(student);
//Add Object to List
studentList.Add(student);
//Add Entry to Selection
newStudentSelection.Items.Add(student.ID);
}
private void newStudentSelection_SelectedIndexChanged(object sender, EventArgs e)
{
//Get Selected Item
int index = newStudentSelection.SelectedIndex;
//Display Data
classOutput.Text = studentList[index].Class;
nameOutput.Text = studentList[index].Name;
idOutput.Text = studentList[index].ID.ToString();
passwordOutput.Text = studentList[index].Password;
districtOutput.Text = studentList[index].District;
gradeOutput.Text = studentList[index].Grade.ToString();
countryOutput.Text = studentList[index].Country;
}
For all my life, from where I stand it seems like this program should work. I Intellisense is giving me no styntax errors, and I have attempted to review my logic with fellow amateur programmers in person, but for what ever reason, the data will not output to the controls on the second form. The only I can think of is that somehow by reference variables I pass as arguments to my RetrieveStudentInfo method and such are not actually getting passed somehow, but that shouldn't be correct.
Any advice on this situation would be greatly appreciated.
Related
I'm slightly baffled as to what the reason for this issue is. I'm receiving the error "Form does not contain a definition for 'GetProgressBar' and no accessible extension method 'GetProgressBar' accepting a first argument of Type 'Form' could be found." I'm simply trying to update the progress bar on a different form for a task. Here is method in Form1,
private async void button_patches_Click(object sender, EventArgs e)
{
if (dbConnect.Connection != null)
{
if (dbConnect.Connection.State == ConnectionState.Open)
{
if (textBox1.Text != "")
{
Form form12 = new Form12();
form12.ShowDialog();
ProgressBar progressBar1 = form12.GetProgressBar();
WSUS wsus = new WSUS(dbConnect, textBox1.Text);
Array kbList = wsus.ReadPatchList();
int patchesLength = kbList.Length;
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v => { progressBar1.Value = v; }) ;
await Task.Run(() => AddPatches(wsus, kbList, progress));
}
else { MessageBox.Show("Please select your path for patches file first"); }
}
else { MessageBox.Show("Please open a connection to the database first."); }
}
else { MessageBox.Show("Please open a connection to the database first."); }
}
The error is occurring on the line ProgressBar progressBar1 = form12.GetProgressBar();
Here is my code in Form12 class.
namespace myDBTemplate1.Forms
{
public partial class Form12 : Form
{
public Form12()
{
InitializeComponent();
}
public ProgressBar GetProgressBar()
{
return progressBar1;
}
}
}
progressBar1 is an instance of ProgressBar that I added to the form via visual studio designer. Also, I set my modifier for my progress bar to public although that shouldn't cause this issue. Evidently, creating an instance of Form12 and then calling one of its public methods isn't working here. I have plenty of other classes in this project where I've calling public instance methods on already instantiated objects and they've worked fine. What's the difference here?
It's because GetProgressBar() is defined in Form12 but you trying to access it from variable of Form type which is parent class and does not have the method.
if (textBox1.Text != "")
{
Form form12 = new Form12();
form12.ShowDialog();
Replace Form with Form12 in your form12 variable declaration or simply use var keyword.
I am doing Airline Reservation System using GUI with ASP.NET in C#.
What I want is assign seats for user, after a user assign that seats, that seat cannot be assigned by others again. I try to use increment do this but instead of 1+1 = 2(that means seat number 2 is the next to be assigned), the system gives me 1+1=11. How can I do what I want?
I have 5 interfaces for this, and I need this assigned value stored in whole running process.
This is my code for the reservation button, I have 2 for it, First Class and Economy Class. Only 5 seats for First Class and 15 seats for Economy Class.
How can I do ?
protected void Button1_Click(object sender, EventArgs e)
{
Session["seats"] = "First Class";
if (firstseatnum > 5)
{
MessageBox.Show("Sorry, the first class seats was fully booked. Can you change to economy class?");
Response.Redirect("reservation.aspx");
}
else
{
++firstseatnum;
totalseatnum1 = Convert.ToInt32(firstseatnum+seatnum);
Response.Redirect("~/information.aspx?firstseatnum="+firstseatnum+"&seatnum="+totalseatnum1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["seats"] = "Economy Class";
if (economyseatnum > 20)
{
MessageBox.Show("Sorry, the economy class seats was fully booked. Can you change to first class?");
Response.Redirect("reservation.aspx");
}
else
{
++economyseatnum;
totalseatnum2 = Convert.ToInt32(economyseatnum + seatnum);
Response.Redirect("information.aspx?economyseatnum=" + economyseatnum + "&seatnum="+totalseatnum2);
}
}
Please help me, thank you.
There are several ways to do it:
Query
// Set
var myVariable = "MyData";
Response.Redirect("/NextPage?MyVariable=" + myVariable);
// Get
var data = Request.QueryString["MyVariable"];
Cookie
// Set
var cookie = new HttpCookie("MyVariable");
cookie.Value = "NyData";
Response.Cookies.Add(cookie);
Response.Redirect("/NextPage");
// Get
var data = Request.Cookies["MyVariable"].Value;
Session
// Set
Session["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Session["MyVariable"];
Application (Store Entire Process)
// Set
Application["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Application["MyVariable"];
Also check CodeProject article to see more examples and detailed explanation.
Presumably seatnum is a string.
If so, try
totalseatnum1 = firstseatnum + Convert.ToInt32(seatnum);
and
totalseatnum2 = economyseatnum + Convert.ToInt32(seatnum);
Say I have a list called listOfFruits in my main form. In a second form I've made I want the user to be able to remove items from that list to a second list called removedFruits. Currently I know I can access these lists in my second form simply passing them as parameters in the form constructor. However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form? Because currently any changes to those lists in my second form don't effect the main form's original copy of the lists. If I were to remove 5 fruits from the listOfFruits passed to my second form then after finishing my work the main form would still still have a full listOfFruits and an empty removedFruits. Is there a simple fix to this? Maybe a get/set or a way to add/remove items from the original lists from the second form? Maybe the answer is in some sort of accessor stuff?
EDIT: To clarify; I want to add to one list, and remove from another. Not add/remove to the same list. Not sure if this matters entirely but I figured I'd be specific here in case it does.
EDIT2: I think the issue is I'm copying the original list from the first form and not editing it directly. Can someone fix my code so I can access the original list from my second form instead of making a copy of the list?
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
public List<IOModule> innerIOList;
IOModule cardAdded = null;
public ListSelector(List<IOModule> cardList)
{
this.Text = windowName;
innerIOList = cardList;
InitializeComponent();
InitializeList();
}
private void InitializeList()
{
if (windowName == "Drive")
{
string[] listDrives = { "ACS880", "test" };
listBox1.Items.AddRange(listDrives);
}
else if (windowName == "IOBlock")
{
if (!innerIOList.Any())
{
MessageBox.Show("No cards loaded! Please import cards from IO List.", "Error Empty Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
foreach (IOModule card in innerIOList)
{
cardAdded = card;
listBox1.Items.Add(card.name);
}
}
else if (windowName == "Local Card")
{
string[] listLocals = { "1756-EN2T", "test" };
listBox1.Items.AddRange(listLocals);
}
else if (windowName == "Processor")
{
string[] listProcessors = { "1756-L71S", "test" };
listBox1.Items.AddRange(listProcessors);
}
}
private void addBtn_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
Form1.SetModule(listBox1.SelectedItem.ToString());
Form1.confirmedAdd = true;
this.Close();
}
else if (cardAdded != null)
{
innerIOList.Remove(cardAdded);
}
else
{
MessageBox.Show("No module selected!");
}
}
and here's how I pass the list to that form from my first form:
ListSelector test = new ListSelector(ioList);
test.ShowDialog();
where ListSelector is the name of my second form, and ioList is the list im passing to it.
EDIT3: added more code
"However c# can't do pointers (correct?) so how can I effect the main form's copy of these lists from my second form?"
No, not correct. Any object reference (for instance, of a List<Fruit>) is still very much a pointer to a place in memory, and if you pass the same List<Fruit> object to both Forms, they share the same List.
I don't know why your changes to your listOfFruits don't chow up in your first Form. I would check the following things:
Are you 100% sure you use the same List<Fruit> object in both Forms. (If you create a new List like this: new List<Fruit>(listOfFruits) it is NOT the same List)
Does the first Form have any way of finding out, that the List has changed? Possible using a Timer with recurring checks, or (my favorite) triggering an event when you change something, and subscribe an EventHandler in the first Form to the event.
I assume that you have created a second list in your second form that is filled with the items of the first form's list. Then changes on the second list aren't reflected in the first list. You have to use the same reference of the list.
public Form2(List<Fruit> listOfFruits)
{
this._listOfFruits = listOfFruits;
}
private List<Fruit> _listOfFruits;
Instead using a public field, try to use property and on creating your new ListSelector pass the list to the property.
public partial class ListSelector : Form
{
private string windowName = Form1.typeOfModuleAdded;
private List<IOModule> innerIOList;
IOModule cardAdded = null;
public List<IOModule> CardList
{
get
{
return innerIOList;
}
set
{
innerIOList = value;
InitializeList();
}
}
public ListSelector()
{
this.Text = windowName;
InitializeComponent();
}
When creating your new ListSelector object
ListSelector ls = new ListSelector();
ls.CardList = your mainform list of IOModule here
ls.ShowDialog();
I've a list in a class:
public class LogInList
{
public int AnsNr { get; set; }
public List<LogInList> GetNr()
{
List<LogInList> Nr = new List<LogInList>();
Nr.Add(new LogInList { AnsNr = 101 });
return Nr;
}
}
And I've created a instance of it in my Login form:
public partial class LogIn : Form
{
LogInList Log = new LogInList();
AND in my button in the form I've the following code:
private void button1_Click(object sender, EventArgs e)
{
if (inMatningTextBox.Text == Log.AnsNr.ToString())
{
Ö.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Du har skrivit in fel anställningsnummer!");
}
The thing is, the int value of 'AnsNr' is automatically changed from 101 to 0 when the program starts. I guess that the new Instance is responsible for this? It tracks back to how many Items there is in the list, I guess? How do I go around this? I want to be able to enter '101' to login.. not 0 ;)
Many thanks!
In your code, you are never calling the GetNr method of LogInList, but access the member AnsNr which is (implicitly) initialized with 0.
Perhaps you can achieve your goal using
if ( Log.GetNr().Select( entry => entry.AnsNr ).Contains( Convert.ToInt32( inMatningTextBox.Text ) ) )
{
Ö.ShowDialog();
this.Close();
}
where you would also have to use
include System.Linq;
When you create your form you have this code:
LogInList Log = new LogInList();
It simply creates an instance of LogInList and does not set the value of AnsNr.
Your code doesn't show a call to GetNr, but if it is called there is a second instance of LogInList created and that one does set the value of AnNr to 101.
The first instance value of AnsNr is never set, that's the problem with your code.
I'm having some trouble with my code regarding a Windows Form Application.
I have a form, that requires the user to enter some data for a new record in the database. I can successfully create a new "Order" in my Database. After I do that, I want to open a form that shows the user all details of the order. Therefore I take an already existing window and want the bindingSource to jump to a certain position.
My Code is as follows:
The "newOrder form"
//do stuff for the creation
//open a customerDetails window with the new entry
//resolve index of the new item
int newIndex = ordersBindingSource.Find("OrderID", newOrderID);
//create a new window and pass the index in the constructor
Order orderDetailsView = new Order(newIndex);
//show the new window and dispose the old one
orderDetailsView.Show();
this.Close();
this.Dispose();
The "Order form" constructor i'm calling:
public Order(int newIndex)
{
//initialize
InitializeComponent();
//set index and repaint
this.ordersBindingSource.Position = newIndex;
this.ordersBindingSource.ResetCurrentItem();
}
This is simply not working and I get the first entry of the dataset.
What am I doing wrong?
Where do you initialize you BindingSource from "Order form"? Make sure your newIndex <= ordersBindingSource.Count().
Try this:
//Form Order
int currentOrder = 0;
//constructor
public Order(int newIndex)
{
//initialize your variable here
currentOrder = newIndex;
//initialize
InitializeComponent();
}
//Create a void method that sets the BindingSource position
void SetupForm()
{
ordersBindingSource.Position = currentOrder;
}
// Override the OnLoad event and call the SetupForm() method here
protected override OnLoad(EventArgs e)
{
SetupForm();
}