How do I get the SelectedIndex of a DropDownList in a GridView

What I have is a GridView inside a Web User Control. In my GridView I have created an EditItemTemplate that has a DropDownList.

The DropDownlist is populated via an ObjectDataSource. It contains some Lookup values.

When the user edits a row, they can select from a drop down list from the look up values and populate the GridView Row which is bound to a different data source.

I have an event handler for OnSelectedIndexChanged for my DropDownList but it does not seem to be firing. I tried setting AutoPostBack = True, but when I do, the postback resets the selectedvalue back to the original value (probably because of the databinding).
<EditItemTemplate>
                <asp:DropDownList ID="CatDropDownList" runat="server" 
                    DataSourceID="LookupObjectDataSource" DataTextField="LookupValue" 
                    DataValueField="LookupValue" AppendDataBoundItems="true" AutoPostBack="true"
                    ondatabound="CatDropDownList_DataBound" EnableViewState="true"
                    OnSelectedIndexChanged="CatDropDownList_SelectedIndexChanged" 
                    SelectedValue='<%# Bind("Cat") %>'>
                </asp:DropDownList>
 
protected void GridView1_RowUpdating( object sender, GridViewUpdateEventArgs e )
        {
            int index = GridView1.EditIndex;
            GridViewRow row = GridView1.Rows[index];
 
            DropDownList ddl = (DropDownList)row.FindControl("CatDropDownList");
 
            e.NewValues["Cat"] = ddl.SelectedValue;
 
            Category.Text = ddl.SelectedValue;
        }
 
Then I noticed that my selected index was not changing so I tried to see if the event was firing and it was not. I tried to populate a text box to see if it was firing. I did this because I could not put a breakpoint on the below event hander
 
protected void CatDropDownList_SelectedIndexChanged( object sender, EventArgs e )
        {
            int index = GridView1.EditIndex;
            GridViewRow row = GridView1.Rows[index];
 
            DropDownList ddl = (DropDownList)row.FindControl("CatDropDownList");
            Category.Text = ddl.SelectedValue;
        }

Open in new window

QCentricAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

aibusinesssolutionsCommented:
You don't want to post back when the drop down is changed, if you are switching to Edit mode, then selecting a value, then hitting the Update button, then you should capture the value of the drop down in the DataGrid's OnRowUpdating function, using the FindControl function.
CB_ThirumalaiCommented:
Try as said by aibusinesssolutions and in your dropdownlist, set the AutoPostback="falase" and remove the SelectedIndexChanged event handler.
QCentricAuthor Commented:
I changed the autopostback so the value is now false

I removed the OnSelectedIndexChanged event handler

The weird thing now is that I can't catch the breakpoint set in my Gridview OnRowUpdating event handler

I able to catch the event before. I will attach the code in case there is something I have missed
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
    DataSourceID="ListDataSource" onrowupdating="GridView1_RowUpdating">
    <Columns>
 
 
protected void GridView1_RowUpdating( object sender, GridViewUpdateEventArgs e )
        {
            int index = GridView1.EditIndex;
            GridViewRow row = GridView1.Rows[index];
 
            DropDownList ddl = (DropDownList)row.FindControl("CatDropDownList");
 
            e.NewValues["Cat"] = ddl.SelectedValue;
 
        }

Open in new window

JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

aibusinesssolutionsCommented:
It should fire after you click Edit, and then click Update.  If not there is something wrong elsewhere.
QCentricAuthor Commented:
It doesn't fire on either. What else could be in the middle?

When I looked at the source for the page, I had this reference to java script. Does this look right for the update link?

<td><a href="javascript:__doPostBack('ListNotices1$GridView1$ctl10$ctl00','')">Update</a>
aibusinesssolutionsCommented:
Do you have a templatefield for your edit/update column?
QCentricAuthor Commented:
My mistake, the RowUpdaing is firing. It is just for some reason, my breakpoint isn't working.

I wrote to a Label in the event and it worked.

The problem is that the new selected index in the DropDowList seems to be the original one.

No I have a command field. I used the GridView designer, Allow Edit, Allow Delete, here is the code:




 <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
        <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" 
            SortExpression="ID" InsertVisible="False" Visible="False" />

Open in new window

aibusinesssolutionsCommented:
Ok lets take a step back.

You have the dropdownlist in a template field, and you are Binding to the variable "cat".  The update function on a gridview will automatically update the values since the Bind() function is two-way binding.  Is everything else in the row updating the datasource?
QCentricAuthor Commented:
No. I started to focus on the dropdown so much i must have made a change to stopped the datasource from updating.

Why didn't I think of testing that before!

I will give you the code for my GridView while I look at why the binding to the datasource might be wrong
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ListNotices.ascx.cs" Inherits="CMS.Controls.ListNotices" %>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" 
    DataSourceID="ListDataSource" onrowupdating="GridView1_RowUpdating">
    <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
        <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" 
            SortExpression="ID" InsertVisible="False" Visible="False" />
        <asp:HyperLinkField DataNavigateUrlFields="ID" 
            DataNavigateUrlFormatString="~/ViewNotice.aspx?id={0}" DataTextField="ID" 
            HeaderText="Notice Number" NavigateUrl="~/ViewNotice.aspx" 
            SortExpression="ID" />
        <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
        <asp:BoundField DataField="NoticeGrp" HeaderText="NoticeGrp" 
            SortExpression="NoticeGrp" />
        <asp:TemplateField HeaderText="Cat" SortExpression="Cat">
            <EditItemTemplate>
                <asp:DropDownList ID="CatDropDownList" runat="server" 
                    DataSourceID="LookupObjectDataSource" DataTextField="LookupValue" 
                    DataValueField="LookupValue" AppendDataBoundItems="true" AutoPostBack="false"
                    ondatabound="CatDropDownList_DataBound" EnableViewState="true"
                    SelectedValue='<%# Bind("Cat") %>'>
                </asp:DropDownList>
                <asp:ObjectDataSource ID="LookupObjectDataSource" runat="server" 
                    DeleteMethod="Delete" InsertMethod="Insert" 
                    OldValuesParameterFormatString="original_{0}" 
                    onselected="LookupObjectDataSource_Selected" SelectMethod="GetData" 
                    TypeName="CMS.GoogleDocDataTableAdapters.LookupTableAdapter" 
                    UpdateMethod="Update">
                    <DeleteParameters>
                        <asp:Parameter Name="Original_LookupValue" Type="String" />
                        <asp:Parameter Name="Original_LookupName" Type="String" />
                    </DeleteParameters>
                    <UpdateParameters>
                        <asp:Parameter Name="Original_LookupValue" Type="String" />
                        <asp:Parameter Name="Original_LookupName" Type="String" />
                    </UpdateParameters>
                    <InsertParameters>
                        <asp:Parameter Name="LookupValue" Type="String" />
                        <asp:Parameter Name="LookupName" Type="String" />
                    </InsertParameters>
                </asp:ObjectDataSource>
                <asp:Label ID="CatLabel" runat="server"></asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Cat") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Description" HeaderText="Description" 
            SortExpression="Description" />
        <asp:BoundField DataField="RefNo" HeaderText="RefNo" SortExpression="RefNo" />
        <asp:BoundField DataField="Originator" HeaderText="Originator" 
            SortExpression="Originator" />
        <asp:BoundField DataField="Content" HeaderText="Content" 
            SortExpression="Content" />
        <asp:BoundField DataField="Background" HeaderText="Background" 
            SortExpression="Background" />
        <asp:BoundField DataField="AttachmentURL" HeaderText="AttachmentURL" 
            SortExpression="AttachmentURL" Visible="False" />
        <asp:TemplateField HeaderText="Attachment URL" SortExpression="AttachmentURL">
            <EditItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Eval("AttachmentURL") %>'></asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:HyperLink ID="HyperLink1" runat="server" 
                    NavigateUrl='<%# Eval("AttachmentURL", "{0}") %>' 
                    Text='<%# Eval("AttachmentURL") %>'></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ExpiryDate" HeaderText="ExpiryDate" 
            SortExpression="ExpiryDate" />
        <asp:BoundField DataField="PostDate" HeaderText="PostDate" 
            SortExpression="PostDate" />
    </Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ListDataSource" runat="server" DeleteMethod="Delete" 
    InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" 
    SelectMethod="GetData" 
    TypeName="CMS.GoogleDocDataTableAdapters.NoticeTableAdapter" 
    UpdateMethod="Update">
    <DeleteParameters>
        <asp:Parameter Name="Original_ID" Type="String" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="Title" Type="String" />
        <asp:Parameter Name="NoticeGrp" Type="String" />
        <asp:Parameter Name="Cat" Type="String" />
        <asp:Parameter Name="Description" Type="String" />
        <asp:Parameter Name="RefNo" Type="String" />
        <asp:Parameter Name="Originator" Type="String" />
        <asp:Parameter Name="Content" Type="String" />
        <asp:Parameter Name="Background" Type="String" />
        <asp:Parameter Name="AttachmentURL" Type="String" />
        <asp:Parameter Name="ExpiryDate" Type="String" />
        <asp:Parameter Name="PostDate" Type="String" />
        <asp:Parameter Name="Original_ID" Type="String" />
    </UpdateParameters>
    <InsertParameters>
        <asp:Parameter Name="ID" Type="String" />
        <asp:Parameter Name="Title" Type="String" />
        <asp:Parameter Name="NoticeGrp" Type="String" />
        <asp:Parameter Name="Cat" Type="String" />
        <asp:Parameter Name="Description" Type="String" />
        <asp:Parameter Name="RefNo" Type="String" />
        <asp:Parameter Name="Originator" Type="String" />
        <asp:Parameter Name="Content" Type="String" />
        <asp:Parameter Name="Background" Type="String" />
        <asp:Parameter Name="AttachmentURL" Type="String" />
        <asp:Parameter Name="ExpiryDate" Type="String" />
        <asp:Parameter Name="PostDate" Type="String" />
    </InsertParameters>
</asp:ObjectDataSource>

Open in new window

aibusinesssolutionsCommented:
I don't see anything wrong with the gridview, you don't need the extra delete, update and insert parameters for the LookupObjectDatasource, if you want to clean it up a bit.

I noticed you have AppendDataBoundItems="true" on the dropdownlist, that appends items to a control instead of re-populating them, but I don't know if that is messing it up.

Since you want to see if everything else updates, you could take the OnRowUpdating="" out of the datagrid tag, that may be messing things up since it might not be firing the default update events.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
QCentricAuthor Commented:
Still no good. Neither the DropDownList nor the other bound fields are updating.

I set AppendDataBoundItems to false. I removed the OnRowUpdating from the Gridview
aibusinesssolutionsCommented:
Once you get the other fields updating, the dropdown list should update with no problems, since you are using Bind().

I would check the ListDataSource Update function and make sure it is working properly.
QCentricAuthor Commented:
I GOT IT WORKING!

I thought perhaps because it was in a Web User Control, that is why I couldn't debug.

I took the code out of the user control and put it into the page and it all worked, and you were right. i didn't need any code in my code behind cs file.

Thank you for all your help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.