Home > Blockchain >  Show Male if database value is 1 else Female in a DataGridView
Show Male if database value is 1 else Female in a DataGridView

Time:03-21

In my database, I have stored Male / Female as 1 / 0 for Gender. Now I have to show Gender values to the user as Male / Female.
How can I do that in a DataGridView?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim gender_ As Int16
        If (rbMale.Checked = True) Then
            gender_ = 1
        Else
            gender_ = 0
        End If
        conn_.Open()
        Dim command As New SqlCommand("INSERT INTO STUDENT (STUDENTNAME, CONTACT, GENDER) VALUES (@NAME, @CONTACT, @GENDER)", conn_)
        command.Parameters.AddWithValue("@NAME", tb1.Text)
        command.Parameters.AddWithValue("@CONTACT", tb2.Text)
        command.Parameters.AddWithValue("@GENDER", gender_)
        command.Connection = conn_
        command.ExecuteNonQuery()
        MsgBox("Record saved.", MsgBoxStyle.Information)

        LoadData()
        conn_.Close()

    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
End Sub

Private Sub LoadData()
    Try
        Dim command As New SqlCommand("SELECT STUDENTNAME, CONTACT, GENDER FROM STUDENT", conn_)
        Dim dataAdapter_ As New SqlDataAdapter(command)

        Dim dt_ As New DataTable

        dataAdapter_.Fill(dt_)

        dgv_student.DataSource = dt_
    Catch ex As Exception

    End Try
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    rbMale.Checked = True
    LoadData()
End Sub

CodePudding user response:

I think that you should have a related table, as I mentioned in a comment, but if you don't, you can still use a combo box column and bind a local list for the text to be displayed. You can do something like this:

Dim genders = {New With {.Value = CShort(0), .Name = "Female"},
               New With {.Value = CShort(1), .Name = "Male"}}

With genderColumn
    .DisplayMember = "Name"
    .ValueMember = "Value"
    .DataSource = genders
End With

This assumes that genderColumn is a DataGridViewComboBoxColumn that the GENDER column of your STUDENT table is bound to.

CodePudding user response:

Because the requirement of the DataGridView is simply to display read only values, I don't think a combo box is required. You just need to modify the query from:

SqlCommand("SELECT STUDENTNAME, CONTACT, GENDER FROM STUDENT", conn_)

to:

SqlCommand("SELECT STUDENTNAME, CONTACT, 
CASE 
    WHEN GENDER=0 THEN 'Female'
    WHEN GENDER=1 THEN 'Male'
    ELSE 'Unknown'
END AS GENDER
FROM STUDENT", conn_)

to display the literal values.

  • Related