I'm trying to collect data of a user using a small form and insert those to columns of the Student table (db). I was able to insert all information except the user's gender, for which I used two radio buttons (radioButton_male
and radioButton_female
).
Here is the C# code I used: Dashboard form:
private void Btn_Register_Click(object sender, EventArgs e)
{
Obj.StudentName = textBox_studentName.Text;
Obj.Age = int.Parse(textBox_age.Text);
Obj.Gender_m = radioButton_male.Text;
Obj.Gender_f = radioButton_female.Text;
Obj.Contact = int.Parse(textBox_contact.Text);
bool success = Obj.studentAdd(Obj);
if (success)
{
MessageBox.Show("Saved");
}
}
Student class
public string StudentName { get; set; }
public int Age { get; set; }
public string Gender_m { get; set; }
public string Gender_f { get; set; }
public int Contact { get; set; }
_
public bool studentAdd(Student obj)
{
SqlConnection conn = new SqlConnection(myconnstring);
bool success = false;
try
{
string sql = "INSERT INTO Students(FullName, Gender, ContactNo, Age) VALUES (@FullName, @Gender, @ContactNo, @Age)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@FullName", StudentName);
cmd.Parameters.AddWithValue("@Gender", Gender_m);
cmd.Parameters.AddWithValue("@Gender", Gender_f);
cmd.Parameters.AddWithValue("@ContactNo", Contact);
cmd.Parameters.AddWithValue("@Age", Age);
conn.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
success = true;
}
else
{
success = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
} finally
{
conn.Close();
}
return success;
}
I understand that I can't simply assign both entries to single column, but I'm unable to set it right using If Else or any other way. Hope you can assist. Thank you.
You might consider changing the table design to have a first and last name, set gender as a bit which can be expressed as a string and perhaps calculate age from collecting their birth date.
Person class
To view data (normally we format in the app). Note that for calculating age in this case may not be exact, it's good enough to get an idea about obtaining age at runtime rather than stored in a database table as with time the age will be incorrect. Also, phone number assumes a specific format which can fail easily if that format is not given.
Table design (column size can be less than NVARCHAR(MAX))