locked
how to add dropdownlist in gridview while editing? RRS feed

  • Question

  • User1835225731 posted

    hi all,

    I have 1 gridview which display the data from 'MembershipDetails' table, and in the gridview I want to add a dropdownlist which will appear while editing. My problem is the data in the dropdownlist is taken from different table which 'Salutation' table. This is my flow:

    1. Add new SQLDataSource1 from the toolbox and connect it with 'MembershipDetails' and enable it for edit, delete and update using stored procedure

    2. Add another one SQLDataSource2 and connect it with 'Salutation' table. 

    3. At Smart tag of gridview, I click the edit column and convert the Salutation in Selected Value to Template Field

    4. Then I go to Edit Template and change from textbox to dropdownlis

    5. In the DropDownList Tasks menu, choose Edit DataBindings. The SelectedValue property of the DropDownList control is selected in the DataBindings dialog box

    6. Click the Field Binding radio button and select Salutation for Bound To.

    7. Select the Two-way databinding check box.

    8. Lastly, I configure the datasource of the dropdownlist and connect it with SQLDataSource2.

    After I run this program and click the edit, it appear

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

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.ArgumentOutOfRangeException: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
    Parameter name: value


    This is .aspx

    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                        AutoGenerateColumns="False" DataSourceID="SqlDataSource2" PageSize="5" 
                        ShowFooter="True" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" 
                        DataKeyNames="TransNo" >
                        <Columns>
                            <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" 
                                ShowSelectButton="True" />
                            <asp:BoundField DataField="TransNo" HeaderText="TransNo" 
                                SortExpression="TransNo" InsertVisible="False" ReadOnly="True" />
                            <asp:BoundField DataField="Purchaser_ID" HeaderText="Purchaser_ID" 
                                SortExpression="Purchaser_ID" ReadOnly="True" />
                            <asp:TemplateField HeaderText="Salutation" SortExpression="Salutation">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="DropDownList1" runat="server" 
                                        DataSourceID="SqlDataSource5" DataTextField="Salutation" 
                                        DataValueField="Salutation" SelectedValue='<%# Bind("Salutation") %>'>
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Salutation") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                                SortExpression="FirstName" />
                            <asp:BoundField DataField="LastName" HeaderText="LastName" 
                                SortExpression="LastName" />
                            <asp:BoundField DataField="Membership_Type" HeaderText="Membership_Type" 
                                SortExpression="Membership_Type" />
                            
                            <asp:BoundField DataField="Date_Issue" HeaderText="Date_Issue" 
                                SortExpression="Date_Issue" />
                            <asp:BoundField DataField="Total_SPA" HeaderText="Total_SPA" 
                                SortExpression="Total_SPA" />
                            
                        </Columns>
                        <FooterStyle BackColor="#FFFFCC" BorderStyle="None" />
                        <HeaderStyle BackColor="#CCFF66" />
                    </asp:GridView>
                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:testCRMConnectionString %>" 
                        DeleteCommand="DeleteMembership" DeleteCommandType="StoredProcedure" 
                        SelectCommand="SELECT [TransNo], [Purchaser_ID], [Salutation], [FirstName], [LastName], [Membership_Type], [Date_Issue], [Total_SPA] FROM [MembershipDetails] WHERE ([Purchaser_ID]=@Purchaser_ID)" 
                        UpdateCommand="EditMembership" UpdateCommandType="StoredProcedure">
                        <DeleteParameters>
                            <asp:Parameter Name="TransNo" Type="Int32" />
                        </DeleteParameters>
                        <SelectParameters>
                            <asp:ControlParameter ControlID="TextBox1" Name="Purchaser_ID" 
                                PropertyName="Text" />
                        </SelectParameters>
                        <UpdateParameters>
                            <asp:Parameter Name="TransNo" Type="Int32" />
                            <asp:Parameter Name="Purchaser_ID" Type="String" />
                            <asp:Parameter Name="Salutation" Type="String" />
                            <asp:Parameter Name="FirstName" Type="String" />
                            <asp:Parameter Name="LastName" Type="String" />
                            <asp:Parameter Name="Membership_Type" Type="String" />
                            <asp:Parameter Name="Date_Issue" Type="String" />
                            <asp:Parameter Name="Total_SPA" Type="String" />
                        </UpdateParameters>
                    </asp:SqlDataSource>
                    <asp:SqlDataSource ID="SqlDataSource5" runat="server" 
                        ConnectionString="<%$ ConnectionStrings:testCRMConnectionString %>" 
                        SelectCommand="SELECT [Salutation] FROM [Salutation]"></asp:SqlDataSource>
                    <asp:Label ID="Label9" runat="server" ForeColor="Red" style="font-weight: 700"></asp:Label>
                



    In this program, I didn't do any coding behind it. Does anyone know how to solve this because I really don't have any idea to solve it.. TQ

    Tuesday, October 1, 2013 12:24 AM

Answers

  • User1143442848 posted

    Hi,

    According to your description, there is a problem with dropdownlist binding when you edit one row of gridview. I suggest you bind dropdownlist in the GridView1_RowDataBound() event.

    Here is an example for you to refer to and it works well in my lab machine.

    1, code in .aspx

    (Note: please try to remove the SelectedValue='<%# Bind("Salutation") %>' from the aspx file)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ProductID" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="true" />
                    <asp:TemplateField HeaderText="ProductName">
                        <ItemTemplate><%# Eval("ProductName") %>                        
                        </ItemTemplate>
                        <EditItemTemplate>
                             <asp:DropDownList ID="ddlName"  DataTextField="ProductName" DataValueField ="ProductName"  runat="server"></asp:DropDownList>                          
                        </EditItemTemplate>                   
                    </asp:TemplateField>
                      <asp:TemplateField HeaderText="Price">
                        <ItemTemplate><%# Eval("UnitPrice","{0:c}") %>                        
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtPrice" Text='<%# Eval("UnitPrice") %> ' runat="server"></asp:TextBox>
                        </EditItemTemplate>                   
                    </asp:TemplateField>
                      <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
                             <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>
                        </ItemTemplate>
                        <EditItemTemplate>
                             <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
                            <asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>                       
                        </EditItemTemplate>                     
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>      
            <br />              
        </div>
        </form>
    </body>
    </html>
    

    2, code in .cs

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            private void BindData()
            {
                GridView1.DataSource = DataBindByDataSet();
                GridView1.DataBind();
            }
    
    
            private DataSet DataBindByDataSet()
            {
                string conStr = ConfigurationManager.ConnectionStrings["testDBConnectionString3"].ConnectionString;
                string sqlStr = "select ID as ProductID, FirstName as ProductName,Address as UnitPrice from t_person";
                DataSet ds = new DataSet();
                SqlConnection con = new SqlConnection(conStr);
    
                con.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, con);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                ad.Fill(ds);
    
                con.Close();
    
                return ds;
            }
    
            protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView1.EditIndex = e.NewEditIndex;
                BindData();
            }
    
            protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView1.EditIndex = -1;
                BindData();
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //check if is in edit mode
                    if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                    {
                        DropDownList ddlName =
                                  (DropDownList)e.Row.FindControl("ddlName");
    
                        string conStr = ConfigurationManager.ConnectionStrings["testDBConnectionString3"].ConnectionString;
                        string sqlStr = "SELECT [FirstName] as ProductName  FROM [t_person2]"; // here is another table
                        DataSet ds = new DataSet();
                        SqlConnection con = new SqlConnection(conStr);
    
                        con.Open();
                        SqlCommand cmd = new SqlCommand(sqlStr, con);
                        SqlDataAdapter ad = new SqlDataAdapter(cmd);
                        ad.Fill(ds);
    
                        con.Close();
                        ddlName.DataSource = ds;
                        ddlName.DataBind();
    
                        //Bind subcategories data to dropdownlist
                        ddlName.DataTextField = "ProductName";
                        ddlName.DataValueField = "ProductName";
    
                        DataRowView dr = e.Row.DataItem as DataRowView;
                        ddlName.SelectedValue =
                                     dr["ProductName"].ToString();
                    }
                }
    
            }
    

    If you need more assistance, please let me know.

    Best Regards,

    Lisa Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 1, 2013 11:11 PM

All replies

  • User839260933 posted

    Hi

    Please try this. Start by setting DropDownList's AppendDataBoundItems property to true. Next, add the NULL ListItem by adding the following element to the DropDownList so that the declarative markup looks like:

    <asp:DropDownList ID="DropDownList1" runat="server"
                                        DataSourceID="SqlDataSource5" DataTextField="Salutation"
                                        DataValueField="Salutation" SelectedValue='<%# Bind("Salutation") %>' AppendDataBoundItems="true">
    <asp:ListItem Value="6" Text=""></asp:ListItem>
                                    </asp:DropDownList>



    Tuesday, October 1, 2013 2:06 AM
  • User1835225731 posted

    hi Sekhar, 

    Thanks for your reply, I have try that but still got the same error

    Tuesday, October 1, 2013 5:20 AM
  • User839260933 posted

    Hi

    Please place dropdown list binding code on page load() in

     if (!IsPostBack)



    Tuesday, October 1, 2013 5:33 AM
  • User1835225731 posted

    hi sekhar,

    what do you mean by dropdown list binding code? can you give me example

    Tuesday, October 1, 2013 8:43 PM
  • User1143442848 posted

    Hi,

    According to your description, there is a problem with dropdownlist binding when you edit one row of gridview. I suggest you bind dropdownlist in the GridView1_RowDataBound() event.

    Here is an example for you to refer to and it works well in my lab machine.

    1, code in .aspx

    (Note: please try to remove the SelectedValue='<%# Bind("Salutation") %>' from the aspx file)

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ProductID" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="ProductID" HeaderText="Product ID" ReadOnly="true" />
                    <asp:TemplateField HeaderText="ProductName">
                        <ItemTemplate><%# Eval("ProductName") %>                        
                        </ItemTemplate>
                        <EditItemTemplate>
                             <asp:DropDownList ID="ddlName"  DataTextField="ProductName" DataValueField ="ProductName"  runat="server"></asp:DropDownList>                          
                        </EditItemTemplate>                   
                    </asp:TemplateField>
                      <asp:TemplateField HeaderText="Price">
                        <ItemTemplate><%# Eval("UnitPrice","{0:c}") %>                        
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="txtPrice" Text='<%# Eval("UnitPrice") %> ' runat="server"></asp:TextBox>
                        </EditItemTemplate>                   
                    </asp:TemplateField>
                      <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
                             <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" Text="Delete"></asp:LinkButton>
                        </ItemTemplate>
                        <EditItemTemplate>
                             <asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
                            <asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>                       
                        </EditItemTemplate>                     
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>      
            <br />              
        </div>
        </form>
    </body>
    </html>
    

    2, code in .cs

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            private void BindData()
            {
                GridView1.DataSource = DataBindByDataSet();
                GridView1.DataBind();
            }
    
    
            private DataSet DataBindByDataSet()
            {
                string conStr = ConfigurationManager.ConnectionStrings["testDBConnectionString3"].ConnectionString;
                string sqlStr = "select ID as ProductID, FirstName as ProductName,Address as UnitPrice from t_person";
                DataSet ds = new DataSet();
                SqlConnection con = new SqlConnection(conStr);
    
                con.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, con);
                SqlDataAdapter ad = new SqlDataAdapter(cmd);
                ad.Fill(ds);
    
                con.Close();
    
                return ds;
            }
    
            protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView1.EditIndex = e.NewEditIndex;
                BindData();
            }
    
            protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView1.EditIndex = -1;
                BindData();
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //check if is in edit mode
                    if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                    {
                        DropDownList ddlName =
                                  (DropDownList)e.Row.FindControl("ddlName");
    
                        string conStr = ConfigurationManager.ConnectionStrings["testDBConnectionString3"].ConnectionString;
                        string sqlStr = "SELECT [FirstName] as ProductName  FROM [t_person2]"; // here is another table
                        DataSet ds = new DataSet();
                        SqlConnection con = new SqlConnection(conStr);
    
                        con.Open();
                        SqlCommand cmd = new SqlCommand(sqlStr, con);
                        SqlDataAdapter ad = new SqlDataAdapter(cmd);
                        ad.Fill(ds);
    
                        con.Close();
                        ddlName.DataSource = ds;
                        ddlName.DataBind();
    
                        //Bind subcategories data to dropdownlist
                        ddlName.DataTextField = "ProductName";
                        ddlName.DataValueField = "ProductName";
    
                        DataRowView dr = e.Row.DataItem as DataRowView;
                        ddlName.SelectedValue =
                                     dr["ProductName"].ToString();
                    }
                }
    
            }
    

    If you need more assistance, please let me know.

    Best Regards,

    Lisa Zhang

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 1, 2013 11:11 PM
  • User839260933 posted

    Hi 

    Please try this

    protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            private void BindData()
            {
                GridView1.DataSource = GetData(); //Data from database
                GridView1.DataBind();
            }

     

    Wednesday, October 2, 2013 12:49 AM