Refer below sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
Form Design
User Control
Form
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
User Control
C#
private void btnFill_Click(object sender, EventArgs e)
{
this.FillComboBox();
}
private void FillComboBox()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT CustomerId FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
cbCustomers.Items.Add(sdr["CustomerId"]);
}
cbCustomers.SelectedIndex = 0;
}
con.Close();
}
}
}
VB.Net
Private Sub btnFill_Click(sender As Object, e As EventArgs) Handles btnFill.Click
Me.FillComboBox()
End Sub
Private Sub FillComboBox()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT CustomerId FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
cbCustomers.Items.Add(sdr("CustomerId"))
End While
cbCustomers.SelectedIndex = 0
End Using
con.Close()
End Using
End Using
End Sub
Form
C#
private void btnUpdate_Click(object sender, EventArgs e)
{
string selectedId = (ucCustomers.Controls.Find("cbCustomers", true)[0] as ComboBox).SelectedItem.ToString();
string query = "UPDATE Customers SET Name=@Name WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@CustomerId", selectedId);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim selectedId As String = (TryCast(ucCustomers.Controls.Find("cbCustomers", True)(0), ComboBox)).SelectedItem.ToString()
Dim query As String = "UPDATE Customers SET Name=@Name WHERE CustomerId=@CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@CustomerId", selectedId)
cmd.Parameters.AddWithValue("@Name", txtName.Text)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub