I have added a Label and Combobox control in the form also added a Form_Load event.
Please refer this code.
C#
Namespaces
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.PopulateCombobox();
}
private void PopulateCombobox()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [FruitId], [FruitName] FROM [Fruits]", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
this.comboBox1.DisplayMember = "FruitName";
this.comboBox1.ValueMember = "FruitId";
this.comboBox1.DataSource = dt;
}
}
}
}
}
VB
Namespaces
Imports System.Data.SqlClient
Imports System.Configuration
Code
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.PopulateCombobox()
End Sub
Private Sub PopulateCombobox()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using conn As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT [FruitId], [FruitName] FROM [Fruits]", conn)
Using da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Me.comboBox1.DisplayMember = "FruitName"
Me.comboBox1.ValueMember = "FruitId"
Me.comboBox1.DataSource = dt
End Using
End Using
End Using
End Sub
End Class
Database
I have made use of the following table Fruits with the schema as follows.
I have already inserted few records in the table.
You can download database SQL from here.
Screenshot