Hi dorsa,
Put an hiddenfield to verify user has selected any row or not.
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
DataSourceID="EditCourseDB">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" Visible="false"></asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="Title"></asp:BoundField>
<asp:BoundField DataField="Floor" HeaderText="Floor"></asp:BoundField>
<asp:BoundField DataField="Capacity" HeaderText="Capacity"></asp:BoundField>
<asp:BoundField DataField="TypeId" HeaderText="TypeId"></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" Text="Get Value" runat="server" OnClick="GridView_Button_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField ID="hfSelected" runat="server" />
<asp:SqlDataSource ID="EditCourseDB" runat="server" ConnectionString="<%$ ConnectionStrings:KDUIS-v1ConnectionString %>"
SelectCommand="SELECT * FROM [EDU_Room]"></asp:SqlDataSource>
<br />
<asp:Button Text="Save" runat="server" OnClick="Save" />
C#
protected void GridView_Button_Click(object sender, EventArgs e)
{
GridViewRow row = (GridViewRow)(sender as Button).NamingContainer;
hfSelected.Value = GridView2.DataKeys[row.RowIndex].Values[0].ToString();
foreach (GridViewRow row1 in GridView2.Rows)
{
if (row1.RowIndex == row.RowIndex)
{
row1.BackColor = System.Drawing.ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row1.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
}
}
}
protected void Save(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(hfSelected.Value))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Please select any Row');", true);
}
else
{
// Do your task.
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Selected id is : " + hfSelected.Value + "');", true);
}
}
VB.Net
Protected Sub GridView_Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim row As GridViewRow = CType((TryCast(sender, Button)).NamingContainer, GridViewRow)
hfSelected.Value = GridView2.DataKeys(row.RowIndex).Values(0).ToString()
For Each row1 As GridViewRow In GridView2.Rows
If row1.RowIndex = row.RowIndex Then
row1.BackColor = System.Drawing.ColorTranslator.FromHtml("#A1DCF2")
Else
row1.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF")
End If
Next
End Sub
Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
If String.IsNullOrEmpty(hfSelected.Value) Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('Please select any Row');", True)
Else
' Do your task.
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('Selected id is : " & hfSelected.Value & "');", True)
End If
End Sub
Screenshot
![](https://i.imgur.com/m6LyJNy.gif)