WinForms Course Registration/Validation Homework
I just started my C# class for college and I've been having a real tough time trying to get my WinForms Course registration project to work. With this assignment, the only code I needed to write was the code under the courseComboBox_SelectedIndexChanged method and the code under the private void completeRegistrationButton_Click(object sender, EventArgs e) method. I included the validation in the first method but I'm not sure if that needs to be its own file or not. I've inserted the code needed for the courseComboBox_SelectedIndexChanged so it can handle the selection of the courses in the comboBox by validating the selection and adding the course number to the list of registered courses in the ListBox. I've also written the code for the button's event handler method so that when the user clicks the button to submit the completed registration, the program writes the list of registered courses to the output file. Visual Studio says I have no issues but when I run my code, it throws an issue as shown in the last picture. Also when I run the program, the form does not store the classes that I select and I am not able to progress so I'm not sure if that's the courseComboBox_SelectedIndexChanged method acting up or where I'm messing up. For reference, I am referencing the courses project in my WinForms project. This is my first time really submitting anything programming related anywhere so I apologize if I miss some key details I'm trying to insert everything I can think of. I am also really fresh in the programming world so I'm still in the basics. I'd appreciate any help with this, I don't want someone to do it for me, but rather help me find the solution so I can learn what I did wrong and what I'm missing. Thank you.
117 Replies
I'm not very familiar with winforms, but try to change your courses to a BindingList instead of a List, and add courses to that instead
I changed the list to a BindingList but it did not fix my errors. I still have the exception user-unhandled error and am not able to save my selections on the form. Would you have any suggestions on what videos or sites are good resources for WinForms?
Can you paste your code, not photos?
$paste
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/$codegif
BlazeBin - chjgjygibeie
A tool for sharing your source code with the world!
Apologies looking on phone for the moment
What is the data source courseComboBox?
Is it courses?
so that is supposed to be the object on the form that the user will use to make their selections from my understanding.
That drop down box
So the error is complaining that you can't change that items collection right?
From what I'm understanding, yes that's correct. the form won't store the course when the user selects it and continue the loop
So let's look at a couple methods here
This method fires because the the "Selected Index Changed", I'm making a somewhat safe assumption that this is when courseComboBox has a selected index change event raised.
I say somewhat safe because despite what the name of method is, it's actually not correlated to control couseComboBox
so on line 81:
courseComboBox.Items.Add(selectedCourse.CourseTitle);
what do you expect this line to do?I expected that line of code to add the course by its course title to the already registered box
What is the already registered box?
IsRegistered* I apologize
kk let's backwalk this a bit
Firstly we have
private BindingList<Course> courses = new BindingList<Course>();
BindingList has some black magic in the background that should help the control stay current against it's databound collection
so in Form1_Load
We're reading data here
Which fills that same collection, courses, via courses.AddI will ask, the only code I wrote was the code under the two methods i mentioned above. the rest of it was already written by the professor. So would it be safe to change the List to a BindingList if he had wrote it originally as a List?
you can safely change it back
I thought we were solving a different problem
when I mentioned that
see the aforementioned, I'm helping on my phone
now I'm not helping on my phone 🙂
No worries, I should've clarified that's on me
so, back to Form_Load
nah you're fine, I just want to make sure we're on the same page, and that the rest of the code makes some sense
so here,
courseComboBox.DataSource = courses;
we're telling courseComboBox that it's DataSource is that list
which is a List<Course>; for the moment, the easiest way to think of List<Course> is that's a collection of courses and it can ONLY contain courses.
so if you try to add widgets they're the wrong shape and they won't fit
so back to our datasource in form_load
you can see....
Here we're telling courseComboBox that the thing to show in the Box is the "member" CourseNumber
and same for the value
the underlying data, is still a Course, but, to show it you'll use the CourseNumber
again this is all setup you didn't do, but I'm trying explain what was done
@Calen in this method private void courseComboBox_SelectedIndexChanged(object sender, EventArgs e)
is your code right?
and
is the code I've written. Everything else, was already pre-written by the professor
Also, I greatly appreciate the explanations you've provided, it's helped clarify this program
so inside
private void courseComboBox_SelectedIndexChanged(object sender, EventArgs e)
, you've written courseComboBox.Items.Add(selectedCourse.CourseTitle);
you're trying to edit the courseComboBox Items collection and failing here right?Correct
okay, so let's talk about the error first
it's saying "Hey, you can't use the Items collection because I have a different idea of how I want my data to be changed"
so when you set the DataSource it's setting a "flag" in the background that basically says, you can't assign to the property because I'm being managed a different way
BUT
also
the datasource we're using is a list of Course
so when we try to add via Items collections to the the combobox is saying "I can't work that way anymore because I have an external data source
and
even if we could add items that way
a string is a different type of object than a Course, so it doesn't fit.
So what do you expect to have happen with line 81?
You said something earlier
and I'm not certain how that correlates
I had a friend try and help me out with this prior to me coming to the group and that's how he had explained it to me. I'm still trying to get my mind around validation and WinForms
kk
so line 81 I suspect is just wrong, and we should remove it
so let's decompose the method
Course selectedCourse = courseComboBox.SelectedItem as Course;This is called a safe cast, we're trying to cast "SelctedItem" as a "Course"; if SelectedItem was a Cat, then it is NOT a Course, and the result is null
if (selectedCourse == null)So, if it's not a Course, we're going to do what's in the if and here
if (selectedCourse.IsRegistered)If you've already registered for the course, then you we enter into that if does that part make sense?
Yes, that makes sense
okay, so back to the top that method:
Course selectedCourse = courseComboBox.SelectedItem as Course;
here we're getting a "reference" to the selected course, and we're dealing with the object...
so consider the following:
at this point selectedCourse is a "reference" to new Course { CourseNumber = "5678" }
because it's the one we picked in the comboBox
let me change one thing
so now selectedCourse, becase we picked the second one, is Course b
and here
selectedCourse.IsRegistered = true;we set Course b IsRegistered = true through our reference of selectedCourse That bit is really important, becasue we have a reference to b, anything we change on our reference is really just actually b.
With this assignment, he wants us to reference Course project onto the forms project. which is why I added the reference in there.
two different types of references
so
example time
Mayor McCheese
REPL Result: Success
Console Output
Compile: 507.229ms | Execution: 63.568ms | React with ❌ to remove this embed.
In the above example: what is a at the end?
it's okay to guess
A would be b because that's the last thing that was assigned to a
so, a would be 1, becasue we assigned it to b, which was one.
because a and b are "integers" they are "value types"
so they aren't "by reference"
Mayor McCheese
REPL Result: Success
Console Output
Compile: 586.508ms | Execution: 64.063ms | React with ❌ to remove this embed.
now we can get a bit more advanced
So are we seeing what a is in this example as well?
well in the above, we can see that a and b are set as values, and they don't change together, but separately
Mayor McCheese
REPL Result: Success
Console Output
Compile: 600.851ms | Execution: 89.127ms | React with ❌ to remove this embed.
now we have a similar example
but we're using Courses, which are not value types
and we see that a is 0, and b is 1
Mayor McCheese
REPL Result: Success
Console Output
Compile: 570.673ms | Execution: 85.227ms | React with ❌ to remove this embed.
so references work differently
when we assign a to b, we have to references pointing to b, and we've lost the original a
So for this one, you just set two references with their own values and had them print out?
yes, but I wanted you to see that a and b are pointng to the same thing
I just wanted to double check, thank you
kk
so now
Course selectedCourse = courseComboBox.SelectedItem as Course;
selectedCourse is a reference to SelectedItem
so, if we make a change to the details of selectedCourse, we'll be changing SelectedItem
so what this means is...
when you do this.. selectedCourse.IsRegistered = true;
and later try to do it again, if (selectedCourse.IsRegistered)
for the same item
that's why that validation works
make sense?
I'm starting to grasp the concept, its making sense
So next we have
//update the ComboBox displaying the registered courses courseComboBox.Items.Add(selectedCourse.CourseTitle);We don't need to do this at all tell me why
is it because we already referenced our SelectedItem and selectedCourse?
yepper!
we've already done the update
I had a message ready to go...
hint: we already have the refence to the Course
so basically if we remove that line, we have fixed the problem you're having, because we shouldn't need it at all
So I had repeated the same thing over twice but incorrectly with the courseComboBox.Items.Add(selectedCourse.CourseTitle);
sort of yes
it's better to say probably that you already accomplished your intention before adding
courseComboBox.Items.Add(selectedCourse.CourseTitle);
the line courseComboBox.Items.Add(selectedCourse.CourseTitle);
isn't valid at this time, and doesn't really accomplish what the comment says it isI removed that line and began to ran the code and I am getting the messages that the courses are registered, but the courses are not populating on the form and not stopping me after reaching the max amount of credits
now, for a number of reasons
totalCredits += selectedCourse.Credits;
is also wrong, but it's going to work for now
let's tackle that nextWhat is the name of that control?
I double clicked the box in the Form1.cs designer and it populated this code in the Form1.cs
so remember line 81?
that we deleted?
yes
let's add back, BUT
change to
registeredCourseList.Items.Add(selectedCourse.CourseTitle)
and run again
That worked and it allowed me to insert the courses in the box but it did not write out how many credits all of that is total and stop at the max credit hours allowed
sure
so, now winforms databinding is utter trash
Likely this is two controls
with a label on the left and a label on the right
the one where the Text property is 0
is going to have a name
okay, well both will have names
but the one on the right is the one we care about
Complete the code for the event handler method for the ComboBox so that it handles the selection of course in the ComboBox by validating the selection and adding the course number to the list of registered courses in the ListBox.
Complete the code for the button's event handler method so that when the user clicks the button to submit the completed registration, the program writes the list of registered courses to the output file.
Make sure your code is:
Is a syntactically correct, well documented C# console application that compiles and runs without warnings or errors.
Includes the Course class as a reusable library class.
Implements the event handler method for item selection in the ComboBox control correctly.
Implements the event handler method for the submit button correctly.
Writes valid registrations to the registered.courses.txt file with appropriate exception handling.
So these were the requirements for the assignment and I am trying to verify that there needs to be a requirement for limiting the amount of courses and credit hours taken
regardless, the label that is set at 0
You have a the line statusMessageText.Text = "Error reading data: " + ex.Message;
much the same way
we set the value of that lable.Text with the total credits
it's a bit more difficult, because totalCredits is an int
and we can't automatically assign an int to a string, how might we fix that?
Would it be by parsing it? This process sounds familiar
parsing the int would convert from a string to an int
Mayor McCheese
REPL Result: Success
Result: int
Compile: 410.622ms | Execution: 33.347ms | React with ❌ to remove this embed.
Mayor McCheese
REPL Result: Failure
Exception: FormatException
Compile: 403.165ms | Execution: 25.361ms | React with ❌ to remove this embed.
that's not quite what we want
Mayor McCheese
REPL Result: Failure
Exception: CompilationErrorException
Compile: 371.960ms | Execution: 0.000ms | React with ❌ to remove this embed.
in c# there is a couple ways to handle this problem
I'm going to cheat and say look around line 104
The $"?
yes
could we leverage that?
I was thinking that, but I thought it was parsing, but its encapsulation correct?
not really parsing or encapsulating
more like converting
Mayor McCheese
REPL Result: Success
Result: string
Compile: 495.667ms | Execution: 32.751ms | React with ❌ to remove this embed.
Mayor McCheese
REPL Result: Success
Result: string
Compile: 466.595ms | Execution: 40.229ms | React with ❌ to remove this embed.
so knowing the label name you should be able to set the value of the Tex property
So we use $" anytime we need to convert an integer into a string to avoid any conflicting issues?
sort of, it's a way to convert with a string
it doesn't have to be an int
With this, there's also an included unit test, would that also be a helpful way to find out issues in the code and pinpoint where problems come from?
Mayor McCheese
REPL Result: Success
Result: string
Compile: 391.380ms | Execution: 22.242ms | React with ❌ to remove this embed.
If you run the unit test, it might cover if the code works
I don't know what the unit test does
This was the unit test but it is not currently in my project
This won't really help you too much in validating your code
So it's not really necessary then?
I don't see the need for it, but I mean it's not my assignment 🙂
I get that haha
so what still doesn't work?
lemme rebuild
I only ask, as it's nearly midnight my time
I understand, I appreciate you taking time out of your night to help me out with this. thank you
I have one question, in regards to the label, were you referring to line 92 with the credits?
nah, this is after my line 84
totalCredits += selectedCourse.Credits;
after we set totalCredits, we can assign totalCredits to the label
so what are the modifications that I need to do with the totalCredits?
I'm looking for the line with the ints we need to change to a string
well we leave everything as is
we're adding more code
so, we have some label that the text value is 0
what is the name of that label?
Are you asking me to come up with a name or what the label is called? cause I see totalCredits = 0 up top
that is probably a label on your form
I'm not finding that label
hmmmm
so if you right click the zero on the form and select properties
so your label is totalCreditValueLabel
so after we incement total credits
we can set totalCredits to the the "Text" property of totalCreditValueLable
How would that be, I tried but got an error
more like
totalCredits += selectedCourse.Credits;
totalCreditValueLabel.Text = $"{totalCredits}";
Worked like a charm. So, totalCredits += selectedCourse.Credits; reads the credit amount for a class, and then the second valueLabel.Text actually prints out the values of the courses?
yepper
I have to get in a whole different mindset with programming that everything has to be written out.
I really appreciate all the time you've spent in helping me out with this, this works for assignment and I really learned a lot and it made sense what you walked me through with. I noticed you have experience in WPF and that is also something I will be working on as well as ADO.NET with SQL. I don't want to take up much more of your time but if you're available in the future, I'd appreciate getting your .02 on some of that as well if it's needed
sure
I'm more of a desktop hobbyist, I don't write desktop software professionally
so keep that in mind 🙂
I totally understand. Again, thank you for the help with this!
np
I'm headed to bed though
sounds good!