How to make my dropdownlist have always the same index selected

babluplanet 21 Reputation points
2021-06-24T10:03:29.75+00:00

So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?

Developer technologies | ASP.NET | Other
{count} votes

2 answers

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,096 Reputation points
    2021-06-25T03:01:23.553+00:00

    Hi @babluplanet ,
    According to your description,I'm guessing that you want to remain the dropdownlist's value after postback.
    I suggest you could bind dropdownlist value in page load.Just like this:

    if (!IsPostBack)  
                {  
                    DataTable dt = new DataTable();  
                    dt.Columns.AddRange(new DataColumn[2] { new DataColumn("value", typeof(int)),  
                        new DataColumn("text", typeof(string)) });  
                    dt.Rows.Add(1, "test1");  
                    dt.Rows.Add(2, "test2");  
                    DropDownList1.DataSource = dt;  
                     
                    DropDownList1.DataTextField = "text";  
                    DropDownList1.DataValueField = "value";  
                    DropDownList1.DataBind();  
                }  
    

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Albert Kallal 5,586 Reputation points
    2021-06-25T04:49:42.343+00:00

    Ok, I am somewhat perplexed that you want the SAME value for each row?

    I mean, that suggest that the selecting and information comes from a parent record?
    (this thus suggests that the drop selection box should be outside of the grid.

    Now, in this example you COULD move the drop down outside of the grid view – it really would work much the same. But, ok - lets put this dropdown in the grid.

    In this example, we have some people.

    I am going to select a Hotel in the drop down.

    The drop down will apply to every row.

    And we are free to pull ALL kinds of information from that hotel. Let’s pull the hotel name, Hotel city, tax rate and description (so, we can pull 2 or 15 columns of information from that drop down selection).

    So, we have the grid, and the combo box, say like this:

    109237-image.png

    (sorry - posting markup seems to prevent me posting - but we be ok - it not a LOT of markup.

    The trick here is to persist the dropdown global to the form – at least during data binding.

    And we not only persisit the drop index selection, but to save our findings and a lot of code, I persist the data row - that just makes the markup oh so much easieer.

    (so I made HotelRow (the one data row from the dropdown as public.

    The results look like this now:

    109216-image.png

    So the columns from the hotel drop and those that follow are based on the hotel record – not the main rows that drives the grid.

    If you change the dropdown - then all rows change.

    And it quite much classic code. I mean, any dropdown in a grid view has to be setup during the grid data bound event – always been that way.

    The ONLY difference here is we made the drop down selection global to the form (and grid), and not to each row.

    So, the code to load everything up looks like this:

        Public MyHotelIndex As Integer  
        Public HotelRow As DataRow  
        Dim rstHotels As New DataTable  
        Dim rstBookings As New DataTable  
      
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load  
      
            If Not IsPostBack Then  
                LoadGrid()  
                ViewState("rstHotels") = rstHotels  
                ViewState("rstBookings") = rstBookings  
            Else  
                rstHotels = ViewState("rstHotels")  
                rstBookings = ViewState("rstBookings")  
            End If  
      
        End Sub  
      
      
        Sub LoadGrid()  
      
            ' load up the combo box first  
      
            Using cmdSQL As New SqlCommand("SELECT * from tblHotels ORDER BY HotelName",  
                            New SqlConnection(My.Settings.TEST4))  
      
                cmdSQL.Connection.Open()  
                rstHotels.Clear()  
                rstHotels.Load(cmdSQL.ExecuteReader)  
                HotelRow = rstHotels.Rows(0)  
      
      
                ' now load up grid  
                rstBookings.Clear()  
                cmdSQL.CommandText = "SELECT ID, FirstName, LastName, City from People"  
                rstBookings.Load(cmdSQL.ExecuteReader)  
                GridView1.DataSource = rstBookings  
                GridView1.DataBind()  
      
            End Using  
      
        End Sub  
      
        Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound  
      
            If e.Row.RowType = DataControlRowType.DataRow Then  
      
                Dim MyDrop As DropDownList = e.Row.FindControl("cboHotels")  
      
                MyDrop.DataSource = rstHotels  
                MyDrop.DataBind()  
                MyDrop.SelectedIndex = MyHotelIndex  
      
            End If  
      
        End Sub  
      
    

    The only extra part, is we wired up the dropdown list - and this is a wee bit trick here. You can't now select the property sheet for the dropdown. (since it is inside of the grid view). But you CAN STILL create the event. And I wish someone would have taught me what I am about to show you here.

    What you do is start typing in the markup, and you type in the event, and when you hit "=" you get this REALLY nice gemstone of a inteli-sense:

    109217-image.png

    So WHEN you hit the = sign, you get that pop list - and ONE of the choices is to create a new event. When you click on it - don't seem that anything occurred, but WHEN you go back to code behind, you see that the code stub was created for you. So we now just put this extra code in the drop down index change event, and we all good to go:

      Protected Sub cboHotels_SelectedIndexChanged1(sender As Object, e As EventArgs)  
      
            Dim myDrop As DropDownList = sender  
      
            MyHotelIndex = myDrop.SelectedIndex  
            HotelRow = rstHotels(MyHotelIndex)  
      
            GridView1.DataSource = rstBookings  
            GridView1.DataBind()  
      
        End Sub  
    

    All we did was

    Set the global index to the drop.
    Set our global ONE row to the row, and then fire off a rebind to update.

    Also, I am happy to post this as c# - my c# is quite good, but my vb? Well, one hand, handing up-side down with one eye closed and I can still code like crazy.

    0 comments No comments

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.