vb.netif-statementdatagridviewwith-statementdatagridviewcombobox

How to make headers in a DataGridView drop downs, and populate the column based on the value


I am new to VB, and am struggling to figure out how to make this work. I have 3 databases being used on the back end that are populated by forms. I want to create the ability for the users to generate custom reports and export them to a .csv file.

There are roughly 20 values I want to provide options for in the combobox, and I can't find a way to better add these values than to manually enter each of them for all 20 rows (would make for a VERY long public sub) LOL. the below code works, but it won't scale. What can I use other than an IF statement so that the value selected in cmbColumn1 determines how the column is populated from the database?

Public Sub btnViewReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewReport.Click
    Dim OleDBC As New OleDbCommand
    Dim OleDBDR As OleDbDataReader
    Dim c As Integer
    c = 0
    If cmbColumn1.Text = "Patient ID" Then

        With OleDBC
            .Connection = conn
            .CommandText = "SELECT * FROM tblPatientsRecord WHERE PatientID like '%" & txtSearch.Text & "%'"
        End With
        OleDBDR = OleDBC.ExecuteReader
        DataGridViewReport.Rows.Clear()
        If OleDBDR.HasRows Then
            While OleDBDR.Read
                DataGridViewReport.Rows.Add()
                DataGridViewReport.Item(0, c).Value = OleDBDR.Item(0)

                c = c + 1
            End While
        Else
        End If
    End If
End Sub    

Solution

  • Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim comboBoxHeaderCell1 As ComboBox = New ComboBox()
            comboBoxHeaderCell1.DropDownStyle = ComboBoxStyle.DropDownList
            comboBoxHeaderCell1.Visible = True
            comboBoxHeaderCell1.Items.Add("Column1")
            comboBoxHeaderCell1.Items.Add("Column2")
            dataGridView1.Controls.Add(comboBoxHeaderCell1)
            comboBoxHeaderCell1.Location = Me.dataGridView1.GetCellDisplayRectangle(0, -1, True).Location
            comboBoxHeaderCell1.Size = Me.dataGridView1.Columns(0).HeaderCell.Size
            comboBoxHeaderCell1.Text = "Column1"
        End Sub