Adding a new entry to a drop-down list when clicking its "Add new" line

riddlesinmymind 6 Reputation points
2021-06-09T10:20:50.48+00:00

I have a drop-down list that is connected to a MS Access database, showing a specific records of the database. I've also added a line to the drop down list in the code-behind which displays "Add New".
When clicking on "Add New", I want my webpage to throw a window with a textbox and a button, allowing me to add a new entry to my drop-down list as well as insert it into my database.

Inserting data into my database isn't a problem, but how do I get the webpage to realize that I want to add a new entry when clicking on "Add New"? I suspect that I need an event of some sort, but events aren't my strong point.

P.S. The drop-down list is named: "ddlauthors".

My aspx page looks like this:

  1. <body>
  2. <form id="form1" runat="server">
  3. <asp:DropDownList ID="ddlauthors" runat="server" Height="29px" Width="205px" >
  4. <asp:ListItem>Add new</asp:ListItem>
  5. </asp:DropDownList>
  6. </form>
  7. </body>

and this is the code-behind

  1. protected void authorddl()
  2. {
  3. string connStr = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
  4. OleDbConnection ConnectionString2 = new OleDbConnection(connStr);
  5. ConnectionString2.Open();
  6. string asking = String.Format(("SELECT [Skrywer naam] from [skrywer name]"));
  7. OleDbCommand com = new OleDbCommand(asking, ConnectionString2);
  8. try
  9. {
  10. OleDbDataReader reader = com.ExecuteReader();
  11. ddlauthors.DataSource = reader; //bind aan die reader-maw sny die DataSet uit
  12. ddlauthors.DataTextField = "Skrywer naam"; //vul die skrywer name in die lys//die woorde in "" is
  13. die kollom se naam en lyk presies so in db
  14. ddlauthors.DataBind();
  15. ddlauthors.Items.Insert(0, new ListItem() { Text = "Add new", Value = "0" });
  16. reader.Close();
  17. }
  18. finally
  19. {
  20. ConnectionString2.Close();
  21. }
  22. }

Can someone please help me?
riddlesinmymind

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,494 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Albert Kallal 5,251 Reputation points
    2021-06-10T05:46:12.253+00:00

    Ok, this is of course a “common” ability here.

    Even for say desktop software (say access), we often had a few combo boxes, and it was a pain when you needed a “new” value in the drop list. Close the form, go to the table or some other form to edit the drop down table, add the row, and then go back to the form – real hassle.

    So, how to do this with web based?

    Well, it really quite much the same idea here.

    However, we need a simple (low code solution) dialog to pop up, the user can enter a new value, we add that new value to the combo box (dropdown list), re-load combo box and we all for the better – no need to exit out of the current form.

    However, to accomplish this in web land?

    Well, we will have to write a “wee bit” of browser side code.

    And for dialogs in web land?

    I really suggest you adopt jQuery.UI. I suspect you already have jQuery in this project. So, I would add jQuery.UI.

    There are a LOT of ways to do this – but let go with a popup addin – jQuery.UI I think is about the best you can find.

    For this example, I’ll include the “CDN” version. (CDN means content delivery network). That just means you don’t have to go and find jQuery.UI – but I would of course consider to download the jquery + jquery.UI, and add them to your project.

    And I will assume that this combo box is a classic one in which we store the “PK” id, but want the text to display. You can reduce/remove the extra settings if this is not your case.

    So, assume this this markup in your page:

    104095-cbomarkpng.png

    With above? Double click on the Add button (we will hide this in a bit.

    So, the code for that add button is this:

    Protected Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click  
    
        Debug.Print("add row code here - user text = " & txtNewHotel.Text)  
    
        ' add a new hotel to table  
        ' (but only if user did enter somme text  
    
        If txtNewHotel.Text <> "" Then  
    
            Using cmdSQL As New OleDbCommand("INSERT into tblHotels (HotelName) Values(*anonymous user*)",  
                            New OleDbConnection(My.Settings.AccessTest2))  
                cmdSQL.Parameters.Add("*anonymous user*", OleDbType.VarWChar).Value = txtNewHotel.Text  
                cmdSQL.Connection.Open()  
                cmdSQL.ExecuteNonQuery()  
    
                cmdSQL.Parameters.Clear()  
                cmdSQL.CommandText = "SELECT ID, HotelName from tblHotels ORDER BY HotelName"  
    
                LoadCombo2(cmdSQL)  
    
                cmdSQL.Dispose()  
    
            End Using  
    
            ' lets be nice and select the row we just added  
            cboHotels.ClearSelection()  
            cboHotels.Items.FindByText(txtNewHotel.Text).Selected = True  
    
            Debug.Print("cbo TEXT value      = " & cboHotels.SelectedItem.Text)  
            Debug.Print("cbo Value (id)   = " & cboHotels.SelectedItem.Value)  
            Debug.Print("cbo index selection = " & cboHotels.SelectedIndex)  
    
        End If  
    

    Ok, and the rest of the code behind is this:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  
    
        If IsPostBack = False Then  
            LoadCombo()  
        End If  
    End Sub  
    
    Sub LoadCombo()  
    
        Using cmdSQL As New OleDbCommand("SELECT ID, HotelName from tblHotels ORDER BY HotelName",  
                        New OleDbConnection(My.Settings.AccessTest2))  
    
            cmdSQL.Connection.Open()  
            LoadCombo2(cmdSQL)  
            cmdSQL.Dispose()  
    
        End Using  
    
    End Sub  
    
    Sub LoadCombo2(cmdSQL As OleDbCommand)  
    
        ' load cbo  
        cboHotels.DataSource = cmdSQL.ExecuteReader  
        cboHotels.DataBind()  
    
        ' add a blank (no select row), and our add new hotel row  
        cboHotels.Items.Insert(0, New ListItem("Add New Hotel", -2))  
        cboHotels.Items.Insert(0, New ListItem("", -1))  
    
    End Sub  
    
    Protected Sub cboHotels_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboHotels.SelectedIndexChanged  
    
    
        If cboHotels.SelectedItem.Text = "Add New Hotel" Then  
    
            ' pop the dialog for add new hotel  
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "My Load script", "AskAddHotel()", True)  
    
        End If  
    
    End Sub  
    

    So, that's about quite much it.

    So double click on the Add button - put in the add button code.

    THEN change the markup to hide the button like this display none.

    But do the double click before hand first.

    ok, so now we see this:

    104085-cbodrop.png

    So by using that button.click trick, then 99% of this code is clean, easy and is code behind. We did have ONE wee bit of client side JS code, but it was and is kept to minimum.

    ------------------ EDIT ----------------------------------

    Ok, so lets do a c# version. And lets do this with a single combo box (one column) as opposed to two columns. And lets do a example WITHOUT that fancy nice popup box.

    To make things simple, then we not be "all fancy pants", and to eliminate the need for that JavaSrcipt?

    Lets drop the combo on the form, and place a button beside the drop down list. This will not be as "fancy" as the first example, but we thus don't need to write really any client side scripts, or even use jQuery.

    So, lets keep this simple. drop the dropdown list, and beside it we will have a "+" button to add to the dropdown list new items - still not too bad - but MUCH more simple.

    So, our markup can look like this:

    104402-mk1.png

    so now the user can select any from the drop down, but to add, we have that simple standard and plane jane button beside the drop down.

    So, simple = less code!!

    And code as c# to run the above? Ok, removing the extra features - bare bones, we get this:

           protected void Page_Load(object sender, EventArgs e)  
            {  
                if (IsPostBack == false)  
                    LoadCombo();  
            }  
      
            public void LoadCombo()  
            {  
       using (OleDbCommand cmdSQL =   
                     new OleDbCommand("SELECT HotelName from tblHotels ORDER BY HotelName",  
                     new OleDbConnection(Properties.Settings.Default.AccessDB)))  
                {  
                    cmdSQL.Connection.Open();  
                    LoadCombo2(cmdSQL);  
                    cmdSQL.Dispose();  
                }  
            }  
      
            public void LoadCombo2(OleDbCommand cmdSQL)  
            {  
      
                // load cbo  
                cboHotels.DataSource = cmdSQL.ExecuteReader();  
                cboHotels.DataBind();  
      
                // add a blank (no select row)  
                cboHotels.Items.Insert(0, new ListItem(""));  
            }  
      
      
            protected void cmdAdd_Click(object sender, EventArgs e)  
            {  
                // add new hotel  
      
                // add a new hotel to table  
                using (OleDbCommand cmdSQL =   
                              new OleDbCommand("INSERT into tblHotels (HotelName) Values(*anonymous user*)",  
                              new OleDbConnection(Properties.Settings.Default.AccessDB)))  
                {  
                    cmdSQL.Connection.Open();  
      
                    cmdSQL.Parameters.Add("*anonymous user*", OleDbType.VarWChar).Value = txtHotelName.Text;  
                    cmdSQL.ExecuteNonQuery();  
      
                    cmdSQL.Parameters.Clear();  
                    cmdSQL.CommandText = "SELECT HotelName from tblHotels ORDER BY HotelName";  
                    LoadCombo2(cmdSQL);  
      
                    cmdSQL.Dispose();  
                }  
      
                // lets be nice and select the row we just added  
                cboHotels.ClearSelection();  
                cboHotels.Items.FindByText(txtHotelName.Text).Selected = true;  
            }  
    

    The results now look like this:

    104328-mk3.png

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.