Assign two inputs to a single column of SQL table

370 Views Asked by At

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).

enter image description here

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool? Gender { get; set; }
    public string GenderType => Gender != null && Gender.Value ? "Male" : "Female";
    public DateTime? BirthDay { get; set; }
    public string PhoneNumber { get; set; }
    public override string ToString() => $"{FirstName} {LastName}";
}

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.

SELECT Id, 
       FirstName, 
       LastName,
       CASE
           WHEN Gender = 1
           THEN 'Male'
           ELSE 'Female'
       END AS Gender, 
       FORMAT(BirthDay, 'MM/dd/yyyy') AS BirthDay, 
       CONVERT(int,ROUND(DATEDIFF(hour,BirthDay,GETDATE())/8766.0,0)) AS Age,
       SUBSTRING(phoneNumber, 1, 3) + '-' + 
       SUBSTRING(phoneNumber, 4, 3) + '-' + 
       SUBSTRING(phoneNumber, 7, 4) AS PhoneNumber
FROM dbo.People;

Table design (column size can be less than NVARCHAR(MAX))

CREATE TABLE dbo.People
(Id          INT IDENTITY(1, 1) NOT NULL, 
 FirstName   NVARCHAR(MAX) NULL, 
 LastName    NVARCHAR(MAX) NULL, 
 Gender      BIT NULL, 
 BirthDay    DATETIME2(7) NULL, 
 PhoneNumber NVARCHAR(MAX) NULL, 
 CONSTRAINT PK_People PRIMARY KEY CLUSTERED(Id ASC)
)

enter image description here

0
On

Your design should just maintain a single field recording the student gender:

public string StudentName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public int Contact { get; set; }

When you collect the form data from your UI, you should assign either 'M' or 'F' depending on the radio button chosen.