How to fill a combobox with a data stored in a table in sql server?....
Can we use stored procedure to do so?

I tryed this code but it keeps giving an error message:
"An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll"
What does that mean????

My code:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connString As String = "server=(local);database=AdvantEdge;trusted_connection=yes"
Dim conn As New SqlConnection(connString)
' fillComboBox1()
Dim strSQL As String = "Select * From Disk"
Dim DA As New SqlDataAdapter(strSQL, conn)
Dim DS As New DataSet
DA.Fill(DS, "Disk")
'Create and populate the DataTable to bind to the ComboBox:
Dim dt As New DataTable
dt.Columns.Add("Disk_Name", GetType(System.String))
dt.Columns.Add("Disk_Key", GetType(System.String))
' Populate the DataTable to bind to the Combobox.
Dim drDSRow As DataRow
Dim drNewRow As DataRow
For Each drDSRow In DS.Tables("Disk").Rows()
drNewRow = dt.NewRow()
drNewRow("Disk_Name") = drDSRow("Disk_Name")
drNewRow("Disk_Key") = drDSRow("Disk_Key")
dt.Rows.Add(drNewRow)
Next
'Bind the DataTable to the ComboBox by setting the Combobox's DataSource property to the DataTable. To display the "Description" column in the Combobox's list, set the Combobox's DisplayMember property to the name of column. Likewise, to use the "Code" column as the value of an item in the Combobox set the ValueMember property.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
With ComboBox1
.DataSource = dt
.DisplayMember = "Disk_Name"
.ValueMember = "Disk_Key"
.SelectedIndex = 0
End With
End Sub

Dani AI

Generated

@siana_j86: The SqlException you saw usually means the database rejected the command or the app could not open the connection — it is a server-side error, not a UI problem. To diagnose, capture and inspect the exception (SqlException.Message and the SqlException.Errors collection) and run the same SELECT or stored procedure in SQL Server Management Studio to see the exact error text.

Quick checklist and common causes:

  • Verify the connection string and that the SQL Server instance is running and reachable (instance name, firewall, integrated vs SQL auth).
  • Make sure the table and column names really exist and are spelled correctly; watch for reserved words (for example a column called date should be bracketed: [date]).
  • Confirm the account has SELECT permission on the table or stored proc.
  • Do not call ExecuteNonQuery for SELECT statements (that was suggested in 's post) — use SqlDataAdapter.Fill or ExecuteReader.
  • Wrap DB code in Using blocks and a Try/Catch so you can log full exception details.

How to wire the ComboBox and show a balance on selection:

  • Fetch only the columns you need (id, display name and, if convenient, the latest current_balance). Binding the DataTable directly is simplest: set the ComboBox DisplayMember to the name column and ValueMember to the id.
  • If you need the latest balance when the user picks a name, do one of two things: include current_balance in the query that fills the ComboBox and read it from the bound SelectedItem (a DataRowView), or on SelectedIndexChanged call a parameterized query / stored proc such as SELECT TOP 1 current_balance FROM tb_credit WHERE customer_id = @cid ORDER BY credit_id DESC to get the latest value. Both approaches avoid fragile string concatenation and extra errors.

Yes, stored procedures are fine — set CommandType to StoredProcedure and fill a DataTable the same way. For immediate debugging run the SQL directly in SSMS, log the full SqlException, and only set SelectedIndex after confirming there are rows. This ties together the earlier suggestions from , and while avoiding the ExecuteNonQuery pitfall noted in ’s reply.

Recommended Answers

All 6 Replies

The error message most likely means that there is an error in one of the sql statements.
which line do you get the error message? which SQL server are you using?

just use this code& place loaddrp() in page_load
where tablename is"table1" & field to b populated inside dropdownlist is "ID"......

Public Function loaddrp() As String
Dim str As String = "select ID from table1"
Dim con As String = ConfigurationManager.AppSettings("preeconn")
Dim com As New SqlCommand(str, New SqlConnection(con))
com.Connection.Open()
Dim ds As New SqlDataAdapter(str, con)
Dim da As SqlDataReader
'ds.Fill(da, "table1")
da = com.ExecuteReader
While da.Read
drp1.Items.Add(da("ID"))
End While
End Function


===========
regards....
preetham

Hai friends,

I have a table tb_credit fields are

credit_id
date
customer_id
account
amount current_balance

I want to display the current balance of a particular customer in billing form ,
I wrote stored procedure

ALTER PROCEDURE usp_Select_BillNoCredit
(
    @customer_id bigint,
    @available float output
)
as
begin   
    select @available = tb_credit.current_balance from tb_credit where credit_id = (select max(credit_id) from  tb_credit where tb_credit.customer_id = @customer_id)
end

In business layer

  public static double SelectAvailableBalance(long _cid)
        {
            try
            {

                SqlParameter[] arParams = new SqlParameter[2];
                arParams[0] = new SqlParameter("@customer_id", _cid);
                arParams[1] = new SqlParameter("@current_balance", SqlDbType.Float);
                arParams[1].Direction = ParameterDirection.Output;
                SqlHelper.ExecuteNonQuery(StaticInfo.SqlConnectionString, "usp_Select_BillNoCredit", arParams);
                return Convert.ToDouble(arParams[1].Value);
            }
            catch (Exception oEx)
            {
                MessageBox.Show(oEx.Message, StaticInfo.MsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return 0;
            }

        }

in code name changed,

 private void cbname_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lblAviBal.Text = Convert.ToString(bizBillReport.SelectAvailableBalance(Convert.ToInt32(cbname.SelectedValue)));

            }
            catch (Exception oEx)
            {
                MessageBox.Show(oEx.Message, StaticInfo.MsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //PostGridBill();
        }

But cant retrive the balance

help me friends this is correct or not

do you mean you want to fill in the display texts of the combobox with the column values from the database? if i am correct, try this code:

Dim conn As New SqlConnection("Data Source = .\sqlexpress ; Initial Catalog = dbname ; Integrated Security = SSPI ")

conn.Open()

Dim sql As New SqlCommand("Select * from disk", conn)
sql.CommandType = CommandType.Text

Dim adapt As New SqlDataAdapter
adapt.SelectCommand = sql
adapt.SelectCommand.ExecuteNonQuery()

Dim dset As New DataSet
adapt.Fill(dset, "disk")

conn.Close()
ComboBox1.DataSource = dset.Tables("disk")
ComboBox1.DisplayMember = "<fieldname>"

i asked not like this, what i want means if i select the name, that time show the current balance of a particular customer name, please help me

can you please make it clear, i cant understand what you want to do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.