如何在DataGridView中创建标题下拉列表,并根据值填充列

时间:2019-11-17 23:33:24

标签: vb.net if-statement datagridview with-statement datagridviewcombobox

我是VB的新手,正在努力弄清楚如何进行这项工作。我在后端使用3个数据库,这些数据库由表单填充。我想为用户提供生成自定义报告并将其导出到.csv文件的功能。

我想在组合框中提供大约20个值,而且我找不到比手动输入所有20行中的每个值更好地添加这些值的方法(这会使公众很长时间子)哈哈。以下代码有效,但无法扩展。除了IF语句外,我还可以使用什么来使cmbColumn1中选择的值确定如何从数据库填充列?

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    

1 个答案:

答案 0 :(得分:0)

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