Can someone pls help me ? I have an ASP.NET page with Gridview(with EDIT and Delete functionlity) and dropdownlist inside it, the Dropdownlist is well populated with the correct values but whenever I click EDIT button in the gridview the selected value in DropDownlist is set to the wrong value(to the first item in the collection) . The data comes from the DB and I am using LIST<T> to pupulate it.
Just to mention that I am Binding Gridview in page_load() event.

Here is the code:

ASP.NET page

<EditItemTemplate>

  <asp:DropDownList ID="ddlVehicleNr" runat="server" 
          AppendDataBoundItems="true">
  </asp:DropDownList>

</EditItemTemplate>

Code Behind Page




 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    Control ctrl = e.Row.FindControl("ddlVehicleNr");
    if (ctrl != null)
    {

    DropDownList ddl = (DropDownList)ctrl;
    VehicleList vehicle = new VehicleList();
    List<Vehicle> lv = InVehicle.GetList(vehicle);

    ddl.DataSource = lv;
    ddl.DataTextField = "VehicleName";
    ddl.DataValueField = "VehicleID";

    if (ddl != null)
    {
    ddl.SelectedValue = ddl.DataValueField;
    ddl.DataBind();
    }

    }

Recommended Answers

All 8 Replies

I notice your dropdownlist doesn't have a datasourceid set so I'm going to guess you're databinding your dropdownlist inside the page load as well. Make sure to put that databinding inside of a !IsPostBack block, otherwise your dropdownlist gets repopulated on every postback which will cause the selected value to reset, which is what appears to be happening here

if (!IsPostBack)
{
    //databind dropdownlist
}

Cheryyhomesj, Thank you for trying to help me.
DatasourceID Property is not required since I am already using DataSource Property.
I am not populating DropdownList in Page_Load event since it is in my Gridview as code shows above. Additional info:
when I put the code in line 33 ddl.SelectedValue = ddl.DataValueField;

This is the Error I get

'ddlVehicleNr' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

without the ddl.SelectedValue = ddl.DataValueField;
program sets always as selected first item in the collection, which is wrong.

Sorry about that, missed the part where you said the drop down was inside the gridview.

if (ddl != null)
{
    ddl.SelectedValue = ddl.DataValueField;
    ddl.DataBind();
}

There's two reasons why this won't work. First, you need to databind the drop down before you set the selected value, otherwise there's nothing to select. Second, right now your telling it to set it's selected value to the string "VehicleID" instead of an actual vehicle id. You will need to get the vehicle id for the current row and set the selectedvalue to that.

Quick example:

string authorID = (row.Cells[1].Controls[0] as TextBox).Text; // Get the primary key for the row

DropDownList ddl = row.FindControl("ddlState") as DropDownList; // Get the drop down list

if (ddl.Items.Count <= 1) // if the drop down is empty or only has default item
{
    ddl.DataSource = GetStateList();
    ddl.DataBind();
}

ddl.SelectedValue = GetStateByAuthorID(authorID); // gets the state for the current row's author

You might need to use a different cell index and control index to get the primary key for your row depending on which column it's in. If you are not including the key in the row and you have the DataKeyNames property of the gridview set then you could use that to get the key

string key = MyGridView.DataKeys[row.RowIndex].Value.ToString();

Sorry but I still face the same problem.

post your updated code

Hi Cherryhomesj,
Here is my code and aspx page, I really don't understand what is going on.
When I bind Gridview the values in Gridview are Correct, once I click Edit button in the Gridview the dropdownlist is wel populated with correct values but always jumps to the first Item in the DropDownList collection loosing the selected value which is correct in the GridView. For Your Info I only bind once in the Page_Load checking if (!Page.IsPostBack).

       ASPX GridView Definition in my Program:

       <asp:GridView ID="GridView1" runat="server" CellPadding="0" ForeColor="#333333" GridLines="None"
            AutoGenerateColumns="false" Width="100%" 
            OnRowEditing="EditRow"
            OnRowCancelingEdit="CancelEditRow" 
            OnRowUpdating="UpdateRow"
            OnRowDataBound="GridView1_RowDataBound" 
            DataKeyNames="ReportID"
            OnRowDeleting="DeleteRow" 
            AllowPaging="true" PageSize="15" 
            OnPageIndexChanging="ChangePage">
            <Columns>
                <asp:TemplateField HeaderText="" HeaderStyle-HorizontalAlign="Justify">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" ValidationGroup="upd" ></asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" ValidationGroup="Upd" ></asp:LinkButton>
                        <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="false" ></asp:LinkButton>
                    </EditItemTemplate>

                </asp:TemplateField>
                <asp:TemplateField HeaderText="Card Nr" HeaderStyle-HorizontalAlign="Justify">
                   <ItemTemplate>
                       <asp:Label ID="lblIndexNrG" runat="server" Text=' <%#Eval("IndexNr") %> '></asp:Label>
                 </ItemTemplate>
                 </asp:TemplateField>

                <asp:TemplateField HeaderText="Full Name" HeaderStyle-HorizontalAlign="Justify">
                    <ItemTemplate>
                       <%#Eval("FirstName") %>
                       <%#Eval("LastName") %> 
                    </ItemTemplate>
                </asp:TemplateField>


                <asp:TemplateField HeaderText="Staff IN/OUT" HeaderStyle-HorizontalAlign="Justify">
                  <ItemTemplate>
                       <%#Eval("StaffINOUT")%>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Left" ></HeaderStyle>
                    <EditItemTemplate>
                       <asp:DropDownList ID="ddlStaffINOUT" runat="server" SelectedValue='<%#Bind("StaffINOUT") %>'>
                            <asp:ListItem Text="IN" Value="IN"></asp:ListItem>
                            <asp:ListItem Text="OUT" Value="OUT"></asp:ListItem>
                      </asp:DropDownList>

                    </EditItemTemplate>
                </asp:TemplateField>

                 <asp:TemplateField HeaderText="Vehicle Nr" HeaderStyle-HorizontalAlign="Justify">
                    <ItemTemplate>

                    <asp:Label ID="lblVehicle" runat="server" Text=' <%#Eval("Vehicle") %> '></asp:Label>
                     <asp:Label ID="lblVehicleNr"  runat="server" Text=' <%#Eval("VehicleID") %> '></asp:Label>
                    </ItemTemplate>

                       <EditItemTemplate>

                            <asp:DropDownList ID="ddlVehicleNr"  runat="server" AppendDataBoundItems="true" AutoPostBack="True" > 

                             </asp:DropDownList>

                    </EditItemTemplate>
                </asp:TemplateField>


                <asp:TemplateField HeaderText="Vehicle IN/OUT" HeaderStyle-HorizontalAlign="Justify">
                    <ItemTemplate>
                    <%#Eval("VehicleINOUT") %>

                    </ItemTemplate>


                    <EditItemTemplate>
                            <asp:DropDownList ID="ddlVehicleINOUT" runat="server" SelectedValue='<%#Bind("VehicleINOUT") %>'>
                            <asp:ListItem Text="IN" Value="IN"></asp:ListItem>
                            <asp:ListItem Text="OUT" Value="OUT"></asp:ListItem>
                      </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>


                <asp:TemplateField HeaderText="" HeaderStyle-HorizontalAlign="Justify">
                    <ItemTemplate>
                        <span onclick="return confirm('Are you sure you want to delete?')">
                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" CausesValidation="False" ></asp:LinkButton>
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <AlternatingRowStyle BackColor="White" ></AlternatingRowStyle>
            <EditRowStyle BackColor="#efefef" ></EditRowStyle>
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" ></FooterStyle>
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" ></HeaderStyle>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" ></PagerStyle>
            <RowStyle BackColor="#EFF3FB" ></RowStyle>
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" ></SelectedRowStyle>
            <SortedAscendingCellStyle BackColor="#F5F7FB" ></SortedAscendingCellStyle>
            <SortedAscendingHeaderStyle BackColor="#6D95E1" ></SortedAscendingHeaderStyle>
            <SortedDescendingCellStyle BackColor="#E9EBEF" ></SortedDescendingCellStyle>
            <SortedDescendingHeaderStyle BackColor="#4870BE" ></SortedDescendingHeaderStyle>
        </asp:GridView>

Code Behind:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string ValueToSelect = string.Empty;

           if (e.Row.RowType == DataControlRowType.DataRow)
            {

                Control ctrl = e.Row.FindControl("ddlVehicleNr");

                Label LookUpLbl = (Label)e.Row.FindControl("lblVehicleNr"); // I added this label in aspx page, it shows correctly inside the GridView
                                                                      // and it holds correct VehicleID in the Gridview
                if (LookUpLbl != null)
                {

                    ValueToSelect = LookUpLbl.Text;
                }

                if (ctrl != null)
                {

                    DropDownList ddl = (DropDownList)ctrl;
                    VehicleList vehicle = new VehicleList();
                    List<Vehicle> lv = VehicleManager.GetList(vehicle);
                    ddl.DataSource = lv;
                    ddl.DataTextField = "VehicleName"; // This is the name of my field in the Database and Collection
                    ddl.DataValueField = "VehicleID";  // This is the name of my field in the Database and Collection
                    if (ddl != null)
                    {
                        ddl.DataBind();
                        ddl.SelectedValue = ValueToSelect;   
                     }

                }

                Label lblStaffINOUT = e.Row.FindControl("StaffINOUT") as Label;
                String sINOUT = Convert.ToString(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "StaffINOUT").ToString()));


                if (sINOUT == "OUT")
                {
                    lblStaffINOUT = e.Row.FindControl("StaffINOUT") as Label;

                    e.Row.BackColor = System.Drawing.Color.Pink;

                }


            }

        }

You're lblVehicleNr label is only available inside the ItemTemplate, not in the EditItemTemplate. If you run the debugger and step through your code you'll most likely find that the ValueToSelect variable is not getting set to a value. So then you're attempting to set the selected value to an empty string, which doesn't exist.

Cherryhomesj, thank you very much. That was it. Problem solved.

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.