Hi dorsa,
Please refer below sample.
You can't use required field validator in commandfield , So please use below code for validating-
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerId">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" SortExpression="CustomerId"
HeaderStyle-CssClass="header-center" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" HeaderStyle-CssClass="header-center" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country"
HeaderStyle-CssClass="header-center" />
<asp:CommandField SelectText="select" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Right" VerticalAlign="Middle" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
<SelectedRowStyle BackColor="LightCyan" ForeColor="DarkBlue" Font-Bold="true" />
</asp:GridView>
<asp:Button Text="Submit" runat="server" OnClick="Check" />
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
}
}
}
protected void Check(object sender, EventArgs e)
{
if (GridView1.SelectedValue == null)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('please selecte row');", true);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", con)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
da.Fill(dt)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub Check(ByVal sender As Object, ByVal e As EventArgs)
If GridView1.SelectedValue Is Nothing Then
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "alert", "alert('please selecte row');", True)
End If
End Sub
Screenshot
