How to Apply where Query on DataTable object in C# ASP.NET

Follow below code:-

      protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fillgrid();                
            }
        }
        public void fillgrid()
        {
            using (SqlConnection con = new SqlConnection(CS))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from Employee_Details", con);
                SqlDataReader reader = cmd.ExecuteReader();
                DataTable dt = new DataTable();            
                dt.Load(reader);
                if (dt != null)
                {
                    DataRow[] dr = null;
                    dr = dt.Select("Gender='M'");                   
                }
            }
        }

Explanation:-  DataTable is present in using System.Data Namespace

Here in above code we use fillgrid function at page load event. In fillgrid function we create connection with SQL Server database and fetch data from database using select query and apply select query on datatable dt to filter data as shown above.



This screenshot shows the all data in datatable dt and we fetch only gender data in dt.select query. 





Post a Comment

0 Comments