Reputation: 13
Gridview is configured:
<asp:GridView ID="gvApptList" runat="server" CssClass="fullwidth" AutoGenerateColumns="False" DataKeyNames="AppointmentID">
<Columns>
<asp:BoundField DataField="Designer" HeaderText="Designer" SortExpression="Designer" />
<asp:BoundField DataField="AppointmentDTM" HeaderText="Appointment Date" SortExpression="AppointmentDTM" DataFormatString="{0:MM-dd-yyyy hh:mm tt}" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:BoundField DataField="Disposition" HeaderText="Disposition" SortExpression="Disposition" />
<asp:BoundField DataField="AppointmentNotes" HeaderText="Appointment Notes" SortExpression="AppointmentNotes" />
<asp:ButtonField ButtonType="Button" CommandName="viewAppointment" Text="View" />
</Columns>
</asp:GridView>
When I click the "View" button, the gvApptList_RowCommand fires off. COde for it is:
If e.CommandName = "viewAppointment" Then
Dim tApptID As Long
gvApptList.SelectedIndex = e.CommandArgument
If IsNumeric(gvApptList.DataKeys(e.CommandArgument).Value) Then
tApptID = gvApptList.SelectedDataKey.Value
Else
Exit Sub
End If
tbAppointmentID.Text = tApptID
DisplayInfo()
End If
The gvApptList.DataKeys(e.CommandArgument).Value always comes back as nothing. What am I missing here? I have this exact sale code working on other pages.
Upvotes: 1
Views: 4830
Reputation: 7918
Pertinent to your task, the correct syntax using DataKeys
in ASP.NET GridView
control is shown below (re: http://www.codeproject.com/Tips/225352/Nesting-GridView-control-in-ASP-NET, written in C#):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// get data key from selected row
s.SelectParameters[0].DefaultValue =Convert.ToString(((GridView)sender).DataKeys[e.Row.RowIndex].Values["AppointmentID "]);
}
}
You should obtain the reference to the Row
corresponding to the command Button
clicked, then extract the DataKeys
value from that Row
. Also, make sure that underlying DataSource
contains AppointmentID
field in its SELECT query.
Pertinent to your case it may look like the following (see Listing 2)
Listing 2.
protected void ViewButton_OnClick(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow row = btn.NamingContainer as GridViewRow;
string strID = gvApptList.DataKeys[row.RowIndex].Values["AppointmentID"].ToString();
int intID;
if (String.IsNotNullOrEmpty(strID)
{
intID = int.Parse(strID);
}
}
or you may use TryParse()
, Convert()
, etc.
Hope this may help.
Upvotes: 0