• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 277
  • Last Modified:

How to bind a cell in a datagrid to a field in a database table

I'm looking to bind a cell in a data grid to a database field in a database table. I'm using an ODBC Connection to connect to a local access database.
1 Solution

            Dim nColCombo1 As New DataGridViewComboBoxColumn
            With nColCombo1
                .HeaderText = "Item PartNo"
                .Name = "Col_ItemPartNo"
                Result = clsData.FillCombo(nColCombo1, "Items", "ItemId", "ItemPartNo", "Select * From Items ")

                .Width = 100
                .DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
                .AutoComplete = True
                .Visible = True

            End With : dGrid.Columns.Add(nColCombo1)

here is my function :

 Public Function FillCombo(ByRef cBox As Object, ByVal Tbl As String, ByVal IdFld As String, ByVal NameFld As String, ByVal SqsString As String) As String

            ' cBox ur ComboBox    
            ' v_ConnectionString Connection String
            ' Tbl  ur table ( Or View ) name
            ' IdFld  DisplayMember Field
            ' NameFld DisplayMember Field
            ' SqsString Select statment

            Dim Conn As SqlConnection = New SqlConnection(v_ConnectionString)
            Dim Comm As SqlCommand = New SqlCommand(SqsString, Conn)
            Comm.Connection = Conn
            Comm.CommandText = SqsString ' "commandtorun"
            Comm.CommandType = CommandType.Text
            Dim DS As DataSet = New DataSet()

            Dim DA As New SqlDataAdapter(Comm)
            DA.Fill(DS, Tbl)

            Dim dt As New DataTable
            dt.Columns.Add(NameFld, GetType(System.String))
            dt.Columns.Add(IdFld, GetType(System.String))

            With cBox
                .DataSource = DS.Tables(Tbl)  
                .DisplayMember = NameFld
                .IdFld = IdFld
            End With

            Call ClossConn(Conn) ' Closs Current Connection

            Return 0
        Catch ex As Exception

            Return ex.Message

        End Try
    End Function

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now