Solved

Using table as cmbo rowsource in .NET

Posted on 2009-04-08
14
201 Views
Last Modified: 2013-11-26
Hello,

I'm trying to select a couple of columns from a table to display in a combo box.

VBA would be something like me.cbobox.rowsource = "Select something from somewhere"

It's been a WHILE since I've played around with .NET or even VB6 - just trying to get refreshed on some simple functions!

I'm thinking something like:

sSQL = "SELECT EmpID FROM Employees"
me.cboCustodian.rowsource? =  sSQL

not exactly of course... Also... What is the method of defining the bound column? I know that you can't specify how many colums are in a combo box or list box in VB or .NET it just displays however many you specify in your select statement.

All help greatly appreciated!!!!
0
Comment
Question by:c9k9h
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
14 Comments
 
LVL 3

Expert Comment

by:Andy Green
ID: 24097538
I'd use a DataSource control, you dont say what database you have so use the one appropriate for your database.
You can write your SQL into the datasource control, and set the datasource for your dropdown control to the datasource control.
Andy
0
 
LVL 15

Expert Comment

by:spprivate
ID: 24097554

Query="select StudentID, Name From StudentRecord"
com = new sqlcommand
com.commandText = Query
da= new sqldataadapter
dt = new DataTable
da.selectcommand = com
da.fill(dt)
cmb1.DataSource = dt
cmb1.ValueMember = dt.columns("Name").ToString
cmb1.DisplayMembers = dt.columns("StudentID").ToString

Open in new window

0
 

Author Comment

by:c9k9h
ID: 24097645
I'm using VB.NET
0
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
LVL 15

Expert Comment

by:spprivate
ID: 24097711
Here is a full code for you assuming AsP.net with VB.net and SQL Server
<%@ Page language="VB" Debug="false" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" runat="server">
Sub Page_Load(Source As Object, E As EventArgs)
  if Not Page.IsPostBack Then
    Dim oConn As SQLConnection
    Dim oComm As SQLCommand
    Dim oReader As SQLDataReader
    Dim sSQL As String
    Dim sConn As String
 
    sSQL= "SELECT au_id, au_fname + ' ' + au_lname AS AuthorName "
    sSQL+= "FROM Authors"
    sConn= "server=(local);database=pubs;Trusted_Connection=yes"
 
    oConn = New SQLConnection(sConn)
    oConn.Open()
 
    oComm = New SQLCommand(sSQL,oConn)
    oReader = oComm.ExecuteReader()
 
    oAuthors.DataSource = oReader
    oAuthors.DataBind()
  end if
End Sub
 
Sub Go_Click(Src As Object, E As EventArgs)
  SelectedItem.Text = "You picked " & oAuthors.SelectedItem.Text & " (" & _
    oAuthors.SelectedItem.Value & ")."
End Sub
</script>
<html>
<head>
  <title>Populate A Drop-down List From A SQL Server Database</title>
</head>
<body>
<form runat="server">
  Please select an author:
  <asp:DropDownList ID="oAuthors" DataTextField="AuthorName"
DataValueField="au_id" Runat="server" />
  <asp:Button ID="Go" Text="Go" OnClick="Go_Click" Runat="server" />
  <br />
  <br />
  <asp:Label ID="SelectedItem" Runat="server" />
</form>
</body>
</html>

Open in new window

0
 

Author Comment

by:c9k9h
ID: 24097928
I'm using straight VB.NET - Just a windows App


I'm trying to use something like the code below - It's not liking SqlDataAdapter though - stating it is undefined





Try
            conn.Open()
            Dim dat As SqlDataAdapter = New SqlDataAdapter("select EmpID from Employees ", con)
            Dim dt As New DataSet()
            dat.Fill(dt, "table")
            cboCustodian.DataSource = dt.Tables("Employees").DefaultView
            cboCustodian.DisplayMember = "EmpID"
            cboCustodian.ValueMember = "EmpID"
 
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            conn.Close()
        End Try

Open in new window

0
 

Author Comment

by:c9k9h
ID: 24097997
Ooops didn't add
Imports System.Data.SqlClient
0
 
LVL 15

Expert Comment

by:spprivate
ID: 24098041
make sure you have control.databind() as well
0
 

Author Comment

by:c9k9h
ID: 24098079
Okay - It seems like this will work for what I'm trying to accomplish, however, I'm still getting errors in debug....


I'm getting the following error for:

New SqlDataAdapter("select EmpID from Employees ", conn)

"C:\Documents and Settings\diw07\My Documents\Visual Studio Projects\Medical Records Requests2\Form1.vb(289): Overload resolution failed because no accessible 'New' can be called with these arguments:
    'Public Overloads Sub New(selectCommandText As String, selectConnection As System.Data.SqlClient.SqlConnection)': Value of type 'System.Data.OleDb.OleDbConnection' cannot be converted to 'System.Data.SqlClient.SqlConnection'.
    'Public Overloads Sub New(selectCommandText As String, selectConnectionString As String)': Value of type 'System.Data.OleDb.OleDbConnection' cannot be converted to 'String'."




0
 
LVL 15

Expert Comment

by:spprivate
ID: 24098131
Your connection object is 'conn'  but in your statement you have mentioned 'con'
Also please post the whole code including the imports
0
 

Author Comment

by:c9k9h
ID: 24098195
Okay here we go

Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
 
    Inherits System.Windows.Forms.Form
 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
 
        Dim sConnectionString, sSQL As String
 
        'SQL Connection String To Backend
        sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=o:UA\Finance\LTC\MIS\Department\Databases\phone memo backend.mdb"
 
        sSQL = "SELECT EmpID FROM Employees"
 
        Dim conn As New System.Data.OleDb.OleDbConnection(sConnectionString)
        Dim cmd As New System.Data.OleDb.OleDbCommand(sSQL, conn)
        Dim dr As System.Data.OleDb.OleDbDataReader
        conn.Open()
 
        
        conn.Close()
        Dim Newdatasource As DataGridTextBoxColumn
 
        'Populate ComboBox
        Try
            conn.Open()
            Dim dat As SqlDataAdapter = New SqlDataAdapter("select EmpID from Employees ", conn)
            Dim dt As New DataSet()
            dat.Fill(dt, "Employees")
            cboCustodian.DataSource = dt.Tables("Employees").DefaultView
            cboCustodian.DisplayMember = "EmpID"
            cboCustodian.ValueMember = "EmpID"
 
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            '   conn.Close()
        End Try
 
 
 
    End Sub
 
 
End Class

Open in new window

0
 
LVL 15

Accepted Solution

by:
spprivate earned 500 total points
ID: 24098502
Here is the final code.I was using sql data client but your db was access.So i had to use oledb.
Imports System.Data
Imports System.Data.OleDb
 
Public Class Form1
 
    Inherits System.Windows.Forms.Form
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 
 
        Dim sConnectionString, sSQL As String
 
        'SQL Connection String To Backend
        sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Northwind.mdb"
 
        sSQL = "SELECT EmployeeID as empid FROM Employees"
 
        Dim conn As New System.Data.OleDb.OleDbConnection(sConnectionString)
        Dim cmd As New System.Data.OleDb.OleDbCommand(sSQL, conn)
        Dim dr As System.Data.OleDb.OleDbDataReader
        'Populate ComboBox
        Try
            conn.Open()
            Dim dat As OleDbDataAdapter = New OleDbDataAdapter(sSQL, conn)
            Dim dt As New DataSet()
            dat.Fill(dt, "Employees")
            cboCustodian.DataSource = dt.Tables("Employees").DefaultView
            cboCustodian.DisplayMember = "empid"
            cboCustodian.ValueMember = "empid"
 
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            conn.Close()
        End Try
 
 
 
    End Sub
 
 
End Class

Open in new window

0
 

Author Comment

by:c9k9h
ID: 24098792
Okay I think we are almost there... Thank you so much for your help (i've upped the Points)

When running I'm getting the msg box saying "Could not bind to the new display member. Paremeter name:newDisplayMember"

in the combo box i'm getting a ton of rows reading "System.Data.DataRowView"



0
 

Author Comment

by:c9k9h
ID: 24098885
Ah, Nevermind! I'm sorry - I had both the display member and Value set to the same thing! sorry!

Works Perfect!!!
0
 

Author Closing Comment

by:c9k9h
ID: 31568039
VERY Helpful and right on - Thanks so much!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question