I have build a C# Windows Forms app that used Entity Framework(DB first model). For the data I am using a .mdf database file.
The data view of dbo.students:
The Form1 class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
StudentsEntities db = new StudentsEntities();
private void Form1_Load(object sender, EventArgs e)
{
bsStudents.DataSource = db.students.ToList();
dgvStudents.DataSource = bsStudents;
lstResults.DisplayMember = "FullName";
DisplayStudent();
}
// Displaying student info(name & credits) in lables, & refreshes DataGridView
private void DisplayStudent()
{
if (bsStudents.Current != null)
{
lblName.Text = ((student)bsStudents.Current).FullName;
lblCurrent.Text = ((student)bsStudents.Current).CurrentCredits.ToString();
lblTotal.Text = ((student)bsStudents.Current).TotalCredits.ToString();
dgvStudents.Refresh();
}
}
private void bsStudents_CurrentChanged(object sender, EventArgs e)
{
DisplayStudent();
}
// add 1 credit to selected student's current credits
private void btnAdd1_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddToCurrentCredits(1);
DisplayStudent();
lblForm1UserPrompt.Text = "1 credit has been added to the current credits of " + ((student)bsStudents.Current).FullName;
}
// add 3 credits to selected student's current credits
private void btnAdd3_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddToCurrentCredits(3);
DisplayStudent();
lblForm1UserPrompt.Text = "3 credits has been added to the current credits of " + ((student)bsStudents.Current).FullName;
}
// place current credits into total credits of selected student
private void btnAddCurrentToTotal_Click(object sender, EventArgs e)
{
((student)bsStudents.Current).AddCurrentToTotal();
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " current credits were added to their total credits.";
}
// change current credits of selected student to user input
private void btnUpdateCurrentCredits_Click(object sender, EventArgs e)
{
string currentCredits = txtUpdateCurrentCredits.Text;
int currentCreditsNumeric = 0;
// validate user input
if (int.TryParse(currentCredits, out currentCreditsNumeric))
{
((student)bsStudents.Current).UpdateCurrentCredits(currentCreditsNumeric);
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " current crdits have been set to " + currentCredits;
txtUpdateCurrentCredits.Clear();
}
else
{
lblForm1UserPrompt.Text = "Please enter numeric data for current credits.";
txtUpdateCurrentCredits.Clear();
}
}
// change total credits of selected student to user input
private void btnUpdateTotalCredits_Click(object sender, EventArgs e)
{
string totalCredits = txtUpdateTotalCredits.Text;
int totalCreditsNumeric = 0;
// validate user input
if (int.TryParse(totalCredits, out totalCreditsNumeric))
{
((student)bsStudents.Current).UpdateTotalCredits(totalCreditsNumeric);
DisplayStudent();
lblForm1UserPrompt.Text = ((student)bsStudents.Current).FullName + "'s" + " total crdits have been set to " + totalCredits;
txtUpdateTotalCredits.Clear();
}
else
{
lblForm1UserPrompt.Text = "Please enter numeric data for total credits.";
txtUpdateCurrentCredits.Clear();
}
}
// add 1 credit to all student's current credits
private void btnAdd1All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddToCurrentCredits(1);
}
DisplayStudent();
lblForm1UserPrompt.Text = "1 credit has been added to the current credits of all students";
}
// add 3 credits to all student's current credits
private void btnAdd3All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddToCurrentCredits(3);
}
DisplayStudent();
lblForm1UserPrompt.Text = "3 credits have been added to the current credits of all students";
}
// place current credits into total credits of all students
private void btnAddCurrentToTotalAll_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.AddCurrentToTotal();
}
DisplayStudent();
lblForm1UserPrompt.Text = "The current credits of all students have been added to their total credits.";
}
// set current credits to 0 for all students
private void btnSetCurrent0All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.CurrentCredits = 0;
}
DisplayStudent();
lblForm1UserPrompt.Text = "The current credits of all students have been set to 0.";
}
// set total credits to 0 for all students
private void btnSetTotal0All_Click(object sender, EventArgs e)
{
foreach (student s in bsStudents)
{
s.TotalCredits = 0;
}
DisplayStudent();
lblForm1UserPrompt.Text = "The total credits of all students have been set to 0.";
}
// navigate to first element
private void btnFirst_Click(object sender, EventArgs e)
{
bsStudents.MoveFirst();
DisplayStudent();
}
// navigate to preceding element
private void btnPrevious_Click(object sender, EventArgs e)
{
bsStudents.MovePrevious();
DisplayStudent();
}
// navigate to succeeding element
private void btnNext_Click(object sender, EventArgs e)
{
bsStudents.MoveNext();
DisplayStudent();
}
// navigate to last element
private void btnLast_Click(object sender, EventArgs e)
{
bsStudents.MoveLast();
DisplayStudent();
}
// TODO: Maybe improve search
private void txtSearchLastName_TextChanged(object sender, EventArgs e)
{
}
// searches BindingSource for names that start with user input
private void btnSearch_Click(object sender, EventArgs e)
{
List<student> students = new List<student>();
foreach (student s in bsStudents)
{
if (s.StudentLastName.ToLower().StartsWith(txtSearchLastName.Text.ToLower()))
{
students.Add(s);
}
}
if (students.Any())
{
bsStudents.Position = bsStudents.IndexOf(students.First());
lstResults.DataSource = students;
DisplayStudent();
}
else
{
MessageBox.Show("Not found");
}
}
// navigate to name selected in ListBox
private void lstResults_SelectedIndexChanged(object sender, EventArgs e)
{
List<student> students = new List<student>();
foreach (student s in bsStudents)
{
if (s.FullName == lstResults.Text)
{
students.Add(s);
}
}
if (students.Any())
{
bsStudents.Position = bsStudents.IndexOf(students.First());
}
else
{
MessageBox.Show("Not found");
}
}
// create new student & add student to BindingSource
private void btnAddStudent_Click(object sender, EventArgs e)
{
Form2 frmNew = new Form2();
frmNew.ShowDialog();
if (frmNew.stu != null)
{
bsStudents.Insert(0, frmNew.stu);
}
}
// remove student from binding source
private void btnRemove_Click(object sender, EventArgs e)
{
string fullName = ((student)bsStudents.Current).FullName;
bsStudents.RemoveCurrent();
lblForm1UserPrompt.Text = fullName + " has been removed.";
}
// save BindingSource to DB
private void btnSaveToDB_Click(object sender, EventArgs e)
{
db.SaveChanges();
}
// exit app
private void btnExitForm1_Click(object sender, EventArgs e)
{
this.Close();
}
}
The Form2 class:
public partial class Form2 : Form
{
public student stu;
public Form2()
{
InitializeComponent();
lblForm2UserPrompt.Text = "Please enter a first name, last name, current and total credits.";
}
private void btnSave_Click(object sender, EventArgs e)
{
string firstName = txtFirst.Text;
string lastName = txtLast.Text;
string currentCredits = txtCurrentCredits.Text;
int currentCreditsNumeric = 0;
string totalCredits = txtTotalCredits.Text;
int totalCreditsNumeric = 0;
//validate user input
if (!string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName) && int.TryParse(currentCredits, out currentCreditsNumeric) && int.TryParse(totalCredits, out totalCreditsNumeric))
{
// instantiate & initialize student
stu = new student();
stu.StudentFirstName = char.ToUpper(firstName[0]) + firstName.Substring(1);
stu.StudentLastName = char.ToUpper(lastName[0]) + lastName.Substring(1);
stu.CurrentCredits = currentCreditsNumeric;
stu.TotalCredits = totalCreditsNumeric;
lblForm2UserPrompt.Text = "Student has been saved.";
}
else
{
//if user did not entered first or last name
if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(lastName))
{
lblForm2UserPrompt.Text = "Please enter a first and last name.";
}
//if user did not entered a number for current credit
else if (!int.TryParse(currentCredits, out currentCreditsNumeric))
{
lblForm2UserPrompt.Text = "Please enter numeric data for current credits.";
txtCurrentCredits.Clear();
}
//if user did not entered a number for total credit
else
{
lblForm2UserPrompt.Text = "Please enter numeric data for total credits.";
txtTotalCredits.Clear();
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
The student class:
public partial class student
{
public int Id { get; set; }
public string StudentLastName { get; set; }
public string StudentFirstName { get; set; }
public int CurrentCredits { get; set; }
public int TotalCredits { get; set; }
public string FullName
{
get
{
return $"{StudentFirstName} {StudentLastName}";
//return StudentFirstName + " " + StudentLastName;
}
}
public void AddToCurrentCredits(int newCurrentCredits)
{
CurrentCredits += newCurrentCredits;
}
public void AddCurrentToTotal()
{
TotalCredits += CurrentCredits;
CurrentCredits = 0;
}
public void UpdateCurrentCredits(int newCurrentCredits)
{
CurrentCredits = newCurrentCredits;
}
public void UpdateTotalCredits(int newTotalCredits)
{
TotalCredits = newTotalCredits;
}
}
The StudentsEntities class:
public partial class StudentsEntities : DbContext
{
public StudentsEntities()
: base("name=StudentsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<student> students { get; set; }
}
The app runs but not as expected...
These are the bits I am having trouble with:
- I seem to be able to create a new student, & to be able to add them to the BindingSource. I know this because the show up in the DataGridView. But, their id value is always 0. And, I need for the id value to be unique.
- When I save the changes made in the BindingSource to the underlying db file the new students are not saved. If I edit the credits of a student, these edits will save. But, the newly created students will not.
The btnAddStudent_Click method:
private void btnAddStudent_Click(object sender, EventArgs e)
{
Form2 frmNew = new Form2();
frmNew.ShowDialog();
if (frmNew.stu != null)
{
bsStudents.Insert(0, frmNew.stu);
}
}
The student object is then created & provided with values in Form2.
After having added 2 new students & set all current credits to 0 in the BindingSource:
The data view of dbo.students after saving the changes made to the BindingSource:
As you can see the changes made to the students credits changed. But, the number of students did not.
What I am looking for:
- I want for the new student objects to save to the BindingSource with unique ids.
- When I save the changes made to the BindingSource I would like to see new students(if created) in the data view of the dbo.
What do you think?
Thanks in advance for the input.