When I run the row command event from a button on a gridview row I can detect the correct value from any field found on the eventrow.
hidIDwhich is a unique identifier reports correctly for each row as expected.ddlValalways reports the first item in the list and not the currently selected value.Can anyone offer explanation as to why a dropdownlist would not detect the currently selected value when using the command event?
ASP.NET
<asp:GridView ID="gv" runat="Server" AutoGenerateColumns="False" OnRowCommand="gv_RowCommand" EnableModelValidation="False">
<Columns>
<asp:TemplateField HeaderText="Reason Missed" ItemStyle-CssClass="Inline" HeaderStyle-CssClass="NoSort" Visible="false">
<ItemTemplate>
<asp:DropDownList ID="ddl" runat="server" DataSourceID="sqldatasource" DataValueField="ID" DataTextField="Text" AppendDataBoundItems="true">
<asp:ListItem Text="Select ..." Value="0"/>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldatasource" runat="Server" SelectCommand="sp" SelectCommandType="StoredProcedure"/>
VB
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim constring = ConfigurationManager.ConnectionStrings("Con").ConnectionString
sqldatasource.ConnectionString = constring
Bind_gv()
End Sub
Protected Sub gv_RowCommand(sender As Object, e As GridViewCommandEventArgs)
Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = gv.Rows(rowIndex)
Dim ddlVal As Integer = DirectCast(row.FindControl("ddl"), DropDownList).SelectedValue
Dim hidID As Integer = DirectCast(row.FindControl("hidID"), HiddenField).Value
'ETC ...
End Sub
After some further diagnosis I found that:
RowCommandevent is triggered after thePage_Loadevent.RowCommandevent is triggered beforePreRenderevent.The consequences of this are if you bind data in the
Page_Loadevent then this data is bound/rebound before theRowCommandis trigger.If, like I was in my case, you are binding your dropdownlist in the
Page_Loadevent or binding the gridview and a sqldatasource in thePage_Loadthen any clientside changes will be lost prior to theRowCommandbeing triggered as they will reset to their initial values.ANSWER
Bind your gridview in any event after the
RowCommandfires such asOnPreRenderComplete. This way clientside changes will still be available up until theRowCommandevent is triggered.