Hi kana250688,
The only way is to set the DropDownStyle to ComboBoxStyle.DropDownList.
Refer below code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
string constr = @"Data Source=.\SQL2022;Initial Catalog=Northwind;UID=sa;PWD=pass@123;";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT CustomerId, ContactName FROM Customers", con))
{
//Fill the DataTable with records from Table.
DataTable dt = new DataTable();
sda.Fill(dt);
//Insert the Default Item to DataTable.
DataRow row = dt.NewRow();
row[0] = 0;
row[1] = "Please select";
dt.Rows.InsertAt(row, 0);
//Assign DataTable as DataSource.
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "ContactName";
comboBox1.ValueMember = "CustomerId";
}
}
}
private DataTable GetData()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT CustomerId, ContactName FROM Customers";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList
Dim constr As String = "Data Source=.\SQL2022;Initial Catalog=Northwind;UID=sa;PWD=pass@123;"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT CustomerId, ContactName FROM Customers", con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = 0
row(1) = "Please select"
dt.Rows.InsertAt(row, 0)
comboBox1.DataSource = dt
comboBox1.DisplayMember = "ContactName"
comboBox1.ValueMember = "CustomerId"
End Using
End Using
End Sub
Private Function GetData() As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT CustomerId, ContactName FROM Customers"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query, con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
Screenshot