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.
hidID
which is a unique identifier reports correctly for each row as
expected.
ddlVal
always 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:
RowCommand
event is triggered after the Page_Load
event.RowCommand
event is triggered before PreRender
event.The consequences of this are if you bind data in the Page_Load
event then this data is bound/rebound before the RowCommand
is trigger.
If, like I was in my case, you are binding your dropdownlist in the Page_Load
event or binding the gridview and a sqldatasource in the Page_Load
then any clientside changes will be lost prior to the RowCommand
being triggered as they will reset to their initial values.
ANSWER
Bind your gridview in any event after the RowCommand
fires such as OnPreRenderComplete
. This way clientside changes will still be available up until the RowCommand
event is triggered.