Question

add drop down list to data grid

Asked by: mindserve

I have added to button to a cell in a datagrid in a vb6 program.
I would like to a drop down list to the button  to return a value of a field  from another table and I have no idea of how to do this if possible.
Or how to add a datacombo to a datagrid and have it return a value from a field in another table.


 

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-02-04 at 07:28:20ID20873121
Tags

vb6

,

datagrid

Topic

VB Controls

Participating Experts
1
Points
0
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. URGENT !! : Update record in datagrid with help of a dat…
    VB6 Problem: update a record in a datagrid using a datacombo on the datagrid Situation: Master/detail situation: two tables are linked by a third table in which a couple of id's from the 2 tables is stored (many to many relationship). The detail information is shown in a ...
  2. DataCombo binding
    I am using the VB6 DataCombo control. At runtime I want to bind it to a recorset. The recordset is the result of an ADO connection to SQL 7 stored proc. The recordset has the correct data in it. I used the code from the MSDN - "HOWTO: Bind a DataList or DataCombo to ...
  3. A DataCombo Problem
    A major feature of the MSHFlexGrid control is its ability to display hierarchical recordsets—relational tables displayed in a hierarchical fashion. But my client would like to display hierarchical recordsets—relational tables using DataCombos. I wrote a test code shown belove...
  4. Datacombo
    hello there. Ok i have a database using access... what im trying to do is to link my datacombo2 (this contains the companies in my database) and the fields pertaining to it. For a clearer example, let me illustrate my fields for demo table demo_id Company_Name Contac...
  5. how can  I use a datacombo  as a cell  in datagrid
    on my form I want to use a datagrid . how can I use a datacombo as a cell in datagrid ?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: emoreauPosted on 2004-02-04 at 10:07:43ID: 10273263

Add a ListBox and make its visible property to False.


'Add this code to the form declaration

Option Explicit
Dim intColIdx As Integer
 'This will contain the index for the current  cell in the dbgrid
Dim blnListShow As Boolean 'is the list showing or not


Private Sub DBGrid1_ButtonClick(ByVal ColIndex As Integer)
Dim intTop As Integer
intColIdx = ColIndex
If blnListShow = False Then 'if the list is not showing then...
blnListShow = True
List1.Left = DBGrid1.Columns(ColIndex).Left + 360
intTop = DBGrid1.Top + (DBGrid1.RowHeight * (DBGrid1.Row +2))
 List1.Top = intTop
 List1.Width = DBGrid1.Columns(ColIndex).Width + 15
                     List1.Visible = True
                  List1.SetFocus
Else 'if the list is show, hide it
             blnListShow = False
              List1.Visible = False
End If
End Sub


          Private Sub Form_Load()
                blnListShow = False 'initialize
           End Sub

        Private Sub List1_Click()
DBGrid1.Columns(intColIdx).Text = List1.Text
 'set the value of the dbgrid
  List1.Visible = False 'hide the list
        End Sub

                      Private Sub List1_LostFocus()
                          blnListShow = False
                          List1.Visible = False
                      End Sub

 

by: mindservePosted on 2004-02-04 at 13:22:07ID: 10275061

So basically all I have to do then is pass a reference to the listbox, then have that listbox appear for the column when the button is clicked?
Sounds too easy to be true! I will try this and get back to you. Thank you.

 

by: mindservePosted on 2004-02-04 at 16:19:16ID: 10276593

I can't seem to get the button event to show the listbox..
I have a grid on the form and  a listbox.
It shows the button, and it shows the listbox with the correct data from the database..what am I doing wrong here???

----------------------------------------------------------

Option Explicit
Dim intColIdx As Integer
 'This will contain the index for the current  cell in the dbgrid
 Dim adoPrimaryRS As Recordset
Dim blnListShow As Boolean 'is the list showing or not Dim WithEvents adoPrimaryRS As Recordset
Dim mbChangedByCode As Boolean
Dim mvBookMark As Variant
Dim mbEditFlag As Boolean
Dim mbAddNewFlag As Boolean
Dim mbDataChanged As Boolean

Private Sub Form_Load()
Dim db As Connection
  Set db = New Connection
  Dim MyColumns As Columns
  db.CursorLocation = adUseClient
 'db.Open "PROVIDER=MSDataShape;Data PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Xtremeblue\Desktop\Backups\SS2X.mdb;"
db.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Xtremeblue\Desktop\Backups\SS2X.mdb;"

  Set adoPrimaryRS = New Recordset
adoPrimaryRS.Open "SELECT DISTINCT EmployeeID FROM OrderDetails WHERE EmployeeID IS NOT NULL", db, adOpenForwardOnly
  'adoprimaryrs.Open "SHAPE {select AllTotals,CitySalesTax,CountySalesTax,CustomerID,Discount,EmployeeID,InvoiceID,OrderDetailID,ProductID,ProductName,Quantity,SalesPrice,SalesTaxCity,SalesTaxCounty,SalesTaxState,ServiceID,ServiceName,ServicePrice,StateSalesTax,SumOfTax,SumOfTax1,SumOfTax2,TaxTotal,TicketDate,TicketID,TypeService,UnitPrice,UnitsInStock,WholesalePrice from OrderDetails} AS ParentCMD APPEND ({select AllTotals,CitySalesTax,CountySalesTax,CustomerID,Discount,EmployeeID,InvoiceID,OrderDetailID,ProductID,ProductName,Quantity,SalesPrice,SalesTaxCity,SalesTaxCounty,SalesTaxState,ServiceID,ServiceName,ServicePrice,StateSalesTax,SumOfTax,SumOfTax1,SumOfTax2,TaxTotal,TicketDate,TicketID,TypeService,UnitPrice,UnitsInStock,WholesalePrice from OrderDetails } AS ChildCMD RELATE EmployeeID TO EmployeeID) AS ChildCMD", db, adOpenStatic, adLockOptimistic
blnListShow = False 'initialize
  'Dim oText As TextBox
  'Bind the text boxes to the data provider
  'For Each oText In Me.txtFields
    'Set oText.DataSource = adoPrimaryRS
 ' Next
List1.AddItem "" 'add a blank item
Do While Not adoPrimaryRS.EOF  'populate the list box
   List1.AddItem adoPrimaryRS!EmployeeID
   adoPrimaryRS.MoveNext
Loop
adoPrimaryRS.Close
  Set DBgrid1.DataSource = adoPrimaryRS '("ChildCMD").UnderlyingValue
Set MyColumns = DBgrid1.Columns 'create Columns Object
MyColumns.Item(0).Alignment = dbgRight 'right align column data
MyColumns.Item(0).AllowSizing = False  'disable changing of column width
MyColumns.Item(0).Locked = True 'don't allow it to be selected
MyColumns.Item(0).Button = True 'display button when selected
MyColumns.Item(0).Button = True
MyColumns.Item(0).Width = 1000  'set column width to 2000 pixels
  mbDataChanged = False
End Sub

Private Sub DBGrid1_ButtonClick(ByVal ColIndex As Integer)
Dim intTop As Integer
intColIdx = ColIndex
If blnListShow = False Then 'if the list is not showing then...
blnListShow = True
List1.Left = DBgrid1.Columns(0).Left + 360
intTop = DBgrid1.Top + (DBgrid1.RowHeight * (DBgrid1.Row + 2))
 List1.Top = intTop
 List1.Width = DBgrid1.Columns(0).Width + 15
                     List1.Visible = True
                  List1.SetFocus
Else 'if the list is show, hide it
             blnListShow = False
              List1.Visible = False
End If
End Sub


Private Sub List1_Click()
'Set adoPrimaryRS = New Recordset
'Set List1.DataSource = adoPrimaryRS
DBgrid1.Columns(intColIdx).Text = List1.Text
'DBgrid1.Columns(0).Text = List1.Text
Set adoPrimaryRS = New Recordset
Set List1.DataSource = adoPrimaryRS
 'set the value of the dbgrid
  List1.Visible = False 'hide the list
        End Sub

                      Private Sub List1_LostFocus()
                          blnListShow = False
                          List1.Visible = False
                      End Sub

 

by: mindservePosted on 2004-02-04 at 16:20:02ID: 10276596

Note: shaping of the recordset was removed

 

by: emoreauPosted on 2004-02-04 at 17:04:49ID: 10276813

Try
List1.ZOrder 0
before
list1.setfocus

If you place a breakpoint into the buttonclick event, do you reach it?

 

by: mindservePosted on 2004-02-04 at 18:01:57ID: 10277029

Now I get an invalid procedure code or runtime #5

 

by: emoreauPosted on 2004-02-04 at 18:39:36ID: 10277199

On which line?

Looks like your listbox is not enabled or visible.

 

by: emoreauPosted on 2004-02-04 at 18:40:58ID: 10277207

This is working on my PC:

VERSION 5.00
Object = "{CDE57A40-8B86-11D0-B3C6-00A0C90AEA82}#1.0#0"; "MSDATGRD.OCX"
Begin VB.Form frmAssembly
   Caption         =   "Assembly"
   ClientHeight    =   6540
   ClientLeft      =   1104
   ClientTop       =   348
   ClientWidth     =   9096
   KeyPreview      =   -1  'True
   LinkTopic       =   "Form1"
   ScaleHeight     =   6540
   ScaleWidth      =   9096
   Begin MSDataGridLib.DataGrid DataGrid1
      Height          =   3972
      Left            =   240
      TabIndex        =   1
      Top             =   120
      Width           =   7932
      _ExtentX        =   13991
      _ExtentY        =   7006
      _Version        =   393216
      HeadLines       =   1
      RowHeight       =   15
      BeginProperty HeadFont {0BE35203-8F91-11CE-9DE3-00AA004BB851}
         Name            =   "MS Sans Serif"
         Size            =   7.8
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      BeginProperty Font {0BE35203-8F91-11CE-9DE3-00AA004BB851}
         Name            =   "MS Sans Serif"
         Size            =   7.8
         Charset         =   0
         Weight          =   400
         Underline       =   0   'False
         Italic          =   0   'False
         Strikethrough   =   0   'False
      EndProperty
      ColumnCount     =   2
      BeginProperty Column00
         DataField       =   ""
         Caption         =   ""
         BeginProperty DataFormat {6D835690-900B-11D0-9484-00A0C91110ED}
            Type            =   0
            Format          =   ""
            HaveTrueFalseNull=   0
            FirstDayOfWeek  =   0
            FirstWeekOfYear =   0
            LCID            =   1033
            SubFormatType   =   0
         EndProperty
      EndProperty
      BeginProperty Column01
         DataField       =   ""
         Caption         =   ""
         BeginProperty DataFormat {6D835690-900B-11D0-9484-00A0C91110ED}
            Type            =   0
            Format          =   ""
            HaveTrueFalseNull=   0
            FirstDayOfWeek  =   0
            FirstWeekOfYear =   0
            LCID            =   1033
            SubFormatType   =   0
         EndProperty
      EndProperty
      SplitCount      =   1
      BeginProperty Split0
         BeginProperty Column00
         EndProperty
         BeginProperty Column01
         EndProperty
      EndProperty
   End
   Begin VB.ListBox List1
      Height          =   1392
      Left            =   4680
      TabIndex        =   0
      Top             =   4440
      Width           =   1332
   End
End
Attribute VB_Name = "frmAssembly"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Private rstData As ADODB.Recordset

Private Sub DataGrid1_BeforeColEdit(ByVal ColIndex As Integer, ByVal KeyAscii As Integer, Cancel As Integer)
    ' BeforeColEdit is called before the grid enters into
    ' edit mode.  You can decide what happens and whether
    ' standard editing proceeds.  This allows you to
    ' substitute different kinds of editing for the current
    ' cell, as is done here.

    If DataGrid1.Columns(ColIndex).DataField = "Field2" Then

'        ' Let the user edit by entering a key.
'        If KeyAscii <> 0 Then Exit Sub

        ' Otherwise, cancel built-in editing and call the
        ' ButtonClick event to drop down List1.
        Cancel = True
        Call DataGrid1_ButtonClick(ColIndex)
    End If
End Sub

Private Sub DataGrid1_ButtonClick(ByVal ColIndex As Integer)
' Assign the Column object to Co because it will be used more than once.
Dim Co As Column

    Set Co = DataGrid1.Columns(ColIndex)

    ' Position and drop down List1 at the right edge of the current cell.
    If ColIndex = 1 Then
        With List1
            .Left = DataGrid1.Left + Co.Left
            .Top = DataGrid1.Top + DataGrid1.RowTop(DataGrid1.Row)
            .Width = Co.Width
            .Visible = True
            .ZOrder 0
            .SetFocus
        End With
    End If
End Sub

Private Sub DataGrid1_Scroll(Cancel As Integer)
    List1.Visible = False
End Sub


Private Sub List1_DblClick()
    ' When an item is selected in List1, copy its index to the
    ' proper column in DBGrid1, then make List1 invisible.
    DataGrid1.Columns("Field2").Text = List1.List(List1.ListIndex)
    List1.Visible = False
    DataGrid1.SetFocus
End Sub

Private Sub List1_LostFocus()
    ' Hide the list if it loses focus.
    List1.Visible = False
    DataGrid1.SetFocus
End Sub

Private Sub Form_Load()
    Set rstData = New ADODB.Recordset
    With rstData
        .Fields.Append "Field1", adInteger
        .Fields.Append "Field2", adVarChar, 20
        .Open
       
        .AddNew Array("Field1", "Field2"), Array(1, "T1")
        .AddNew Array("Field1", "Field2"), Array(1, "T2")
        .AddNew Array("Field1", "Field2"), Array(1, "T3")
        .AddNew Array("Field1", "Field2"), Array(1, "T4")
        .AddNew Array("Field1", "Field2"), Array(1, "T5")
    End With

    With DataGrid1
        Set .DataSource = rstData
       
        With .Columns(1)
            .Button = True
            .Width = 1500
        End With
    End With
   
    With List1
        .Visible = False
        .AddItem "T1"
        .AddItem "T2"
        .AddItem "T3"
    End With
End Sub



 

by: mindservePosted on 2004-02-05 at 04:26:06ID: 10279780

It's not working when connected to the recordset...

 

by: emoreauPosted on 2004-02-05 at 05:40:31ID: 10280257

I see in your first sample that your column is locked!

Remove this line:
MyColumns.Item(0).Locked = True 'don't allow it to be selected

 

by: mindservePosted on 2004-02-05 at 06:24:29ID: 10280583

I unlocked it and it still didn't work....
Here is a link to what I am trying to do. There is a small zip file you can download with the database actually in it.
I checked the database and the field EmployeeID is updateable as it is text and can have duplicates...
I have no idea of why this is not working.
http://www.jamiegrossfeld.com/helpme.htm

 

by: mindservePosted on 2004-02-05 at 11:16:30ID: 10283330

Well, I found the problem and the solution...

 

by: emoreauPosted on 2004-02-05 at 11:22:41ID: 10283396

What was it?

 

by: mindservePosted on 2004-02-05 at 11:24:43ID: 10283416

adoPrimaryRS.Open "SELECT DISTINCT EmployeeID FROM OrderDetails WHERE EmployeeID IS NOT NULL", db, adOpenDynamic, adLockBatchOptimistic

NOT



adoPrimaryRS.Open "SELECT DISTINCT EmployeeID FROM OrderDetails WHERE EmployeeID IS NOT NULL", db, adOpenForwardOnly

 

by: emoreauPosted on 2004-02-05 at 12:07:48ID: 10283837

will you now close this question?

 

by: mindservePosted on 2004-02-05 at 12:29:59ID: 10284056

Yes, I think so..

 

by: emoreauPosted on 2004-02-05 at 17:32:04ID: 10286343

I really think that I deserve the points. mindserve ask how to add a combo to a grid control and I answered that question.

 

by: mindservePosted on 2004-02-06 at 03:31:28ID: 10289032

No, I asked the question but expected it to work..your answer didn't work and my answer did work and I posted this ..
you don't deserve the points In my opinion.
In that case, anyone could post any answer whether
it worked or not...just post any answer and get the points.......

 

by: mindservePosted on 2004-02-06 at 04:09:58ID: 10289177

One more thing...if you read my initial question again, you clearly can see that I wanted it to attach to a recordset...I did
not simply ask how to get a button to work on a grid which is the code you posted. I wanted to know how to get the values
out of tables.....not just how to put a button on a datagrid.
 I asked something a bit more specific than that. Unfortunately, you
did not read the question clearly and your answer would never have solved my problem:

Initial question:
I have added to button to a cell in a datagrid in a vb6 program.
I would like to a drop down list to the button  to return a value of a field  from another table and I have no idea of how to do this if possible.
Or how to add a datacombo to a datagrid and have it return a value from a field in another table.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...