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 database SQL from here.
HTML
<asp:DropDownList runat="server" ID="ddlCustomers">
</asp:DropDownList>
<br />
Delete Selected Item
<br />
<asp:Button Text="Delete Top" runat="server" OnClick="DeleteSelectedItem" />
Namespaces
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateDropDownList();
}
}
private void PopulateDropDownList()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
ddlCustomers.DataTextField = "Name";
ddlCustomers.DataValueField = "CustomerId";
ddlCustomers.DataSource = dt;
ddlCustomers.DataBind();
}
}
}
}
protected void DeleteSelectedItem(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId", conn))
{
cmd.Parameters.AddWithValue("@CustomerId", this.ddlCustomers.SelectedItem.Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
this.PopulateDropDownList();
}
Screenshots
Selecting the Item to be deleted from table and DropDownList.
After deletion of Item from DropDownList.