Hi All,

I have created a table called tblState in access with 2 columns: id and state and am populating a dropdownlist with state.

I am in need of code to delete a selected value of dropdownlist from database in asp.net2.0 using c#.

Can anybody help me please.

Thanks
Wajid

Dani AI

Generated

Quick summary and root cause: the reason the top item kept getting deleted was that the DropDownList was being rebound on every Page_Load before the button click ran. Page_Load executes on postback before control event handlers, so rebinding resets the selected item back to the first entry. This is the behavior identified — only bind the list on the first page load (not on postbacks), or capture the selected value into a local variable at the top of the click handler before any rebinding happens.

Practical, safer approach: store the table primary key (ID) as the DropDownList value instead of the state text, then delete by that ID with a parameterized command to avoid quoting problems and injection. Use proper disposal for connection/command objects (for example, using blocks) so connections always close. After a successful DELETE, re-bind the list once so the UI matches the database. Note that removing an item from the DropDownList control only changes the UI; as hinted, it does not persist to your Access DB.

Troubleshooting checklist: confirm the list is bound only on initial load (check the Page.IsPostBack flag), verify the DataValueField is the numeric ID and that you read that value before any rebinding, use a parameterized DELETE against the ID, and rebind after deletion. If problems persist, log the selected value at the start of the click handler and check for exceptions from the DB command or Access file locking.

Recommended Answers

All 7 Replies

hi ansari.wajid,
You can easily remove selected items from DropDownList. On the click of Delete button you first take index of selected item and then pass it to the Remove function of DropDownList control.Use following code.

DropDownList_Object.Items.Remove(DropDownList_Object.SelectedIndex);

Hope this will help you. If you have any problem feel free to share with us.
Thanks & Regards
Dilip Kumar Vishwakarma
Programmer
.Net Consulting

Yup, exactly. When a user chooses it, have it either autopostback to the server (or something), then find the selected index, then remove it with the above code. Vuala.

Hello All

I am not a very good programmer, just tryied following code but its not working.

when ever I am pressing delete button after selecting a value in dropdownlist, it just deleting the top most value.

C# CODE:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

public partial class newDeleteValueDDList : System.Web.UI.Page
{
    OleDbConnection cn;
    OleDbCommand cmd;
    DataSet ds;
    OleDbDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        getData();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        connectDatabase();

        string str = DropDownList1.SelectedValue;
                string strDelete = "delete state from tblState where state='" + str + "'";
                cmd = new OleDbCommand(strDelete, cn);
                cmd.ExecuteNonQuery();
                cn.Close();
                getData();

    }
    private void connectDatabase()
    {
        string strConnectionString = Server.MapPath("~/App_Data/dummyDb.mdb");
        cn = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=" + strConnectionString);
        cn.Open();
    }
    private void getData()
    {
        connectDatabase();

        string strSelectState = "select state from tblState order by state";
        da = new OleDbDataAdapter(strSelectState, cn);
        ds = new DataSet();
        da.Fill(ds);

        DropDownList1.DataSource = ds.Tables[0];
        DropDownList1.DataTextField = "state";
        DropDownList1.DataValueField = "state";

        DropDownList1.DataBind();

        cn.Close();
    }
}

DESIGN SOURCE:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Delete" /></div>
    </form>
</body>

ACCESS DATABASE:

ID  STATE
--  -----
10   AAA
20   BBB
30   CCC
40   DDD

I am sending the relevent db and code which has been used in my code

If anybody can help I will be grateful to him.

Thanks
wajid

Your code is fine, its this line:

DropDownList1.SelectedValue;

This is supposed to be:

DropDownList1.SelectedItem.Value;

Hi SheSaidImaPregy

Thanks for your help.
But still its giving the same problem

Thanks Again
Wajid

I'm sorry I missed that completely. One thing, because it is C#, it has to be dropdownlist1.SelectedValue

Also, you need to put your page_load in a "ispostback" statement. The reason why it is deleting the top one is that even during postbacks, the page_Load event is fired. Therefore, your dropdownlist is repopulated via getData();. Since it is repopulated, the selected index is [0], which means when you go to delete your selected value, it grabs the selected index, which is now again defaulted to [0].

To prevent this, you need to put your page_load in a ispostback like:

void page_load..
{
  if (!isPostBack) {
    getData();
  }
}

This way your page_load doesn't fire on a postback, so your selectedindex will remain the same, and the correct value will be deleted.

Hi shesaidimapreggy

Thanks a lot, its working fine now.

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.