Hi smile,
Check this example. Now please take its reference and correct your code.
HTML
<asp:TextBox runat="server" ID="txtNumber" OnTextChanged="TextChanged" AutoPostBack="true" />
<br />
<asp:GridView runat="server" ID="gvEmployees" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="EmployeeId" HeaderText="Id" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView(int top = 3)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT TOP (@Top) EmployeeId,FirstName,LastName,Country FROM Employees ORDER BY NEWID()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Top", top);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
gvEmployees.DataSource = dt;
gvEmployees.DataBind();
}
}
}
}
protected void TextChanged(object sender, EventArgs e)
{
BindGridView(Convert.ToInt32(txtNumber.Text.Trim()));
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridView()
End If
End Sub
Private Sub BindGridView(Optional ByVal top As Integer = 3)
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT TOP (@Top) EmployeeId,FirstName,LastName,Country FROM Employees ORDER BY NEWID()"
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@Top", top)
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
gvEmployees.DataSource = dt
gvEmployees.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub TextChanged(ByVal sender As Object, ByVal e As EventArgs)
BindGridView(Convert.ToInt32(txtNumber.Text.Trim()))
End Sub
Screenshot