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.