Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

GridView Edit Mode DropDownList

Posted on 2008-06-12
3
4,677 Views
Last Modified: 2013-11-26
This will be the third time I've asked this question. The first time, it was ignored completely, the second time, an Expert started working on it, but didn't understand what I was getting at, and after 2 unhelpful suggestions and my responses to them, he just stopped paying attention (so it would seem, as he hasn't replied for over two weeks). So I will ask one more time...

In the code snippet I will post below, you will see how I have a DropDownList inside the EditItemTemplate of my GridView. It is not bound at design time, but rather at run-time, to an XML file. Specifically, when a user clicks "Edit" on a row, it binds the DDL to the XML file and then pre-selects whatever value is displayed in the Label that's in the normal ItemTemplate declaration. This part works perfectly. However, what is NOT working perfectly is that whenever you edit ANY item, be it the DDL value or anything in any of the TextBoxes in other fields, it passes a Null value into the Parameter that's supposed to take the SelectedValue of the DDL. After much consideration, I felt it might be necessary to use a SelectedValue='<%# Bind("Office") %>' declaration in the front-end, but since the DDL isn't bound to anything until "Edit" is clicked, this code throws errors. So there has to be some way to get that value to pass to the stored procedure parameter, I just am lost on how to do it.

I'll post relevant code for the issue below.

Thanks in advance for any help!
<asp:GridView id="gvResult" runat="server" Width="100%" CssClass="salesdirgrid" 
            CellPadding="2" AllowSorting="True" AllowPaging="true"
            DataSourceID="SqlDataSource1" AutoGenerateColumns="False" EmptyDataText="No Records" ShowFooter="True" UseAccessibleHeader="False"
            OnRowDataBound="gvResult_RowDataBound" OnRowEditing="gvResult_RowEditing" DataKeyNames="ID">
			<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#1C66AF" />
			<FooterStyle ForeColor="#4A3C8C" BackColor="#1C66AF" />
			<PagerStyle HorizontalAlign="Left" ForeColor="White" BackColor="#1C66AF" />
            <Columns>
                <asp:BoundField DataField="Office" HeaderText="Office" InsertVisible="False" ReadOnly="True"
                    SortExpression="Office" Visible="False" />
                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                    SortExpression="ID" Visible="False" />
                <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="Desk Location" SortExpression="DeskLoc">
                    <ItemStyle Width="10%" />
                    <ItemTemplate>
                        <asp:Label ID="lblDeskLoc" runat="server" Text='<%# Eval("DeskLoc") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDeskLoc" MaxLength="3" Font-Size="XX-Small" runat="server" Text='<%# Bind("DeskLoc") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="ReqDeskLoc" runat="server" ControlToValidate="txtDeskLoc" Text="*" 
                            ErrorMessage="You must enter a Desk Location" />
                        <asp:RegularExpressionValidator ID="RegDeskLoc" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtDeskLoc" ErrorMessage="Desk Location must be 3 characters" ValidationExpression="^\w{3}$" /> 
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewDeskLoc" runat="server" MaxLength="3" Width="100%" ValidationGroup="OkToValidate" />
                        <asp:RequiredFieldValidator ID="ReqNewDeskLoc" runat="server" ControlToValidate="txtNewDeskLoc" Text="*" 
                            ErrorMessage="You must enter a New Desk Location" ValidationGroup="OkToValidate" />
                        <asp:RegularExpressionValidator ID="RegNewDeskLoc" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtNewDeskLoc" ErrorMessage="Desk Location must be 3 characters" ValidationExpression="^\w{3}$" /> 
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="First Name" SortExpression="FName">
                    <ItemTemplate>
                        <asp:Label ID="lblFName" runat="server" Text='<%# Eval("FName") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtFName" MaxLength="20" Font-Size="XX-Small" runat="server" Text='<%# Bind("FName") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="ReqFName" runat="server" ControlToValidate="txtFName" Text="*" 
                            ErrorMessage="You must enter a First Name" />
                        <asp:RegularExpressionValidator ID="RegFName" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtFName" ErrorMessage="First Names can only use Alpha characters and cannot exceed 20 characters" ValidationExpression="^[a-zA-Z\-\.]{1,20}$" /> 
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewFName" runat="server" MaxLength="20" Width="100%" ValidationGroup="OkToValidate" />
                        <asp:RequiredFieldValidator ID="ReqNewFName" runat="server" ControlToValidate="txtNewFName" Text="*" 
                            ErrorMessage="You must enter a New First Name" ValidationGroup="OkToValidate" />
                        <asp:RegularExpressionValidator ID="RegNewFName" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtNewFName" ErrorMessage="First Names can only use Alpha characters and cannot exceed 20 characters" ValidationExpression="^[a-zA-Z\-\.]{1,20}$" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="Last Name" SortExpression="LName">
                    <ItemTemplate>
                        <asp:Label ID="lblLName" runat="server" Text='<%# Eval("LName") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLName" MaxLength="20" Font-Size="xX-Small" runat="server" Text='<%# Bind("LName") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="ReqLName" runat="server" ControlToValidate="txtLName" Text="*" 
                            ErrorMessage="You must enter a Last Name" />
                        <asp:RegularExpressionValidator ID="RegLName" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtLName" ErrorMessage="Last Names can only use Alpha characters and cannot exceed 20 characters" ValidationExpression="^[a-zA-Z\-\.]{1,20}$" /> 
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewLName" runat="server" MaxLength="20" Width="100%" ValidationGroup="OkToValidate" />
                        <asp:RequiredFieldValidator ID="ReqNewLName" runat="server" ControlToValidate="txtNewLName" Text="*" 
                            ErrorMessage="You must enter a New Last Name" ValidationGroup="OkToValidate" />
                        <asp:RegularExpressionValidator ID="RegNewLName" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtNewLName" ErrorMessage="Last Names can only use Alpha characters and cannot exceed 20 characters" ValidationExpression="^[a-zA-Z\-\.]{1,20}$" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="Phone" SortExpression="Phone">
                    <ItemTemplate>
                        <asp:Label ID="lblPhone" runat="server" Text='<%# Eval("Phone") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtPhone" MaxLength="20" Font-Size="xX-Small" runat="server" Text='<%# Bind("Phone") %>'></asp:TextBox>
                        <asp:RequiredFieldValidator ID="ReqPhone" runat="server" ControlToValidate="txtPhone" Text="*" 
                            ErrorMessage="You must enter a Phone Number" />
                        <asp:RegularExpressionValidator ID="RegPhone" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtPhone" ErrorMessage="Invalid phone number format" ValidationExpression="\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}$|\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}\s?[xX]?\d{4}$" /> 
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtNewPhone" runat="server" MaxLength="20" Width="100%" ValidationGroup="OkToValidate" />
                        <asp:RequiredFieldValidator ID="ReqNewPhone" runat="server" ControlToValidate="txtNewPhone" Text="*" 
                            ErrorMessage="You must enter a New Phone Number" ValidationGroup="OkToValidate" />
                        <asp:RegularExpressionValidator ID="RegNewPhone" runat="server" Display="none" EnableClientScript="false" 
                            ControlToValidate="txtNewPhone" ErrorMessage="Invalid phone number format" ValidationExpression="\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}$|\(?\s*\d{3}\s*[\)\.\-]?\s*\d{3}\s*[\-\.]?\s*\d{4}\s?[xX]?\d{4}$" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="Office" SortExpression="Office">
                    <ItemTemplate>
                        <asp:Label ID="lblOffice" runat="server" Text='<%# Eval("Office") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="ddlOfficeUpdate" Font-Size="XX-Small" runat="server" SelectedValue='<%# Bind("Office") %>' />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlNewOfficeUpdate" Font-Size="XX-Small" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" Text="Edit" CommandName="Edit" CausesValidation="false" />
                        <asp:LinkButton runat="server" Text="Delete" CommandName="Delete" CausesValidation="false" />
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton runat="server" Text="Update" CommandName="Update" CausesValidation="true" />
                        <asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" CausesValidation="false" />
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="lnkAdd" runat="server" Text="Add" Width="80%" CommandName="Insert"
                            CausesValidation="true" ValidationGroup="OkToValidate" OnClick="lnkAdd_Click" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="Wheat" ForeColor="#CC0066" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
		</asp:GridView><br />
		<asp:ValidationSummary ID="ValSum1" runat="server" HeaderText="The record could not be added because of the following:"
		    Font-Bold="true" DisplayMode="BulletList" EnableClientScript="true" ShowMessageBox="true" ShowSummary="true" />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:claimdir %>" DeleteCommand="usp_delete" DeleteCommandType="StoredProcedure"
        SelectCommand="usp_getData" SelectCommandType="StoredProcedure" InsertCommand="usp_newEntry" InsertCommandType="StoredProcedure" UpdateCommand="usp_edit" UpdateCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="ddlOffice" Name="Office" PropertyName="SelectedValue"
                Type="String" ConvertEmptyStringToNull="false" />
            <asp:ControlParameter ControlID="ddlSearchBy" Name="search" PropertyName="SelectedValue"
                Type="String" />
            <asp:ControlParameter ControlID="txtPanel" Name="input" PropertyName="Text" Type="String" />
        </SelectParameters>
        <UpdateParameters>
            <asp:Parameter Name="ID" Type="Int32" />
            <asp:Parameter Name="DeskLoc" Type="String" />
            <asp:Parameter Name="FName" Type="String" />
            <asp:Parameter Name="LName" Type="String" />
            <asp:Parameter Name="Phone" Type="String" />
            <asp:Parameter Name="Office" Type="String" />
        </UpdateParameters>
        <InsertParameters>
            <asp:Parameter Name="DeskLoc" Type="String" />
            <asp:Parameter Name="FName" Type="String" />
            <asp:Parameter Name="LName" Type="String" />
            <asp:Parameter Name="Phone" Type="String" />
            <asp:Parameter Name="Office" Type="String" />
        </InsertParameters>
        <DeleteParameters>
            <asp:Parameter Name="ID" Type="Int32" />
        </DeleteParameters>
    </asp:SqlDataSource>
/////////////////////////////////////////////////////////////////////
CODE-BEHIND
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == gvResult.EditIndex)
            {
                ds = new DataSet();
                ServerPath = Server.MapPath(@"\");
                ds.ReadXml(ServerPath + @"\Library\xml\claimdir\Office.xml");
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlOfficeUpdate");
                ddl.DataTextField = "Text";
                ddl.DataValueField = "Value";
                ddl.DataSource = ds.Tables[0];
                ddl.DataBind();
                ddl.Items[0].Text = "-Choose Office-";
                ddl.SelectedValue = theOffice;
            }
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            ds = new DataSet();
            ServerPath = Server.MapPath(@"\");
            ds.ReadXml(ServerPath + @"\Library\xml\claimdir\Office.xml");
            DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlNewOfficeUpdate"));
            ddl.DataTextField = "Text";
            ddl.DataValueField = "Value";
            ddl.DataSource = ds.Tables[0];
            ddl.DataBind();
            ddl.Items[0].Text = "-Choose Office-";
        }
    }
 
    protected void gvResult_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvResult.EditIndex = e.NewEditIndex;
        theOffice = ((Label)gvResult.Rows[e.NewEditIndex].FindControl("lblOffice")).Text;
    }

Open in new window

0
Comment
Question by:SeTech
  • 2
3 Comments
 
LVL 14

Accepted Solution

by:
Dustin Hopkins earned 500 total points
ID: 21776131
Try adding a gridview updating event handler and then define your parameter value in it.

Hope this helps,
Dustin
 Sub gridview_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles gvResult.RowUpdating
        Dim rowindex As Integer = e.RowIndex
        Dim ddl As DropDownList = gvResult.Rows(rowindex).FindControl("ddlOfficeUpdate")
        SqlDataSource1.UpdateParameters("Office").DefaultValue = ddl.SelectedValue
    End Sub
 
 
Note: if you remove the parameter from teh update parameters list then you can change the above code to this:
 
 Sub gridview_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles gvResult.RowUpdating
        Dim rowindex As Integer = e.RowIndex
        Dim ddl As DropDownList = gvResult.Rows(rowindex).FindControl("ddlOfficeUpdate")
        SqlDataSource1.UpdateParameters.Add("Office", TypeCode.String, ddl.SelectedValue)
    End Sub

Open in new window

0
 

Author Comment

by:SeTech
ID: 21779840
That worked!!! Granted, I had to convert that VB to C#, but it gave me what I was looking for! Thank you!
0
 

Author Closing Comment

by:SeTech
ID: 31466724
Worked like a champ!
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question