Filter ASP.Net GridView using Session in C# and VB.Net

Last Reply one month ago By dharmendr

Posted one month ago

i want to retrieve data to the gridview where emailid should take value from the session "Company" so that i can show perticular loged in compnies data. 

You are viewing reply posted by: dharmendr one month ago.
Posted one month ago

Hi nid@patel,

Check this example. Now please take its reference and correct your code.

HTML

<asp:GridView ID="gvDetails" runat="server">
</asp:GridView>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

VB.Net

Imports System.Data.Configuration
Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["Company"] != null)
        {
            string emailid = Session["Company"].ToString();
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Table WHERE EmailId = @Email";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Email", emailid);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                this.gvDetails.DataSource = dt;
                this.gvDetails.DataBind();
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        If Session("Company") IsNot Nothing Then
            Dim emailid As String = Session("Company").ToString()
            Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
                Dim cmd As SqlCommand = New SqlCommand()
                cmd.CommandText = "SELECT * FROM Table WHERE EmailId = @Email"
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                cmd.Parameters.AddWithValue("@Email", emailid)
                Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                Me.gvDetails.DataSource = dt
                Me.gvDetails.DataBind()
            End Using
        End If
    End If
End Sub