Posts

Showing posts from July, 2016

Add remove class using jquery

We can use jquery to add and remove class to html elements using jquery addClass and removeClass methods. < style >     .myClass {     color : blue ;     }     .primary {     color : black ;     } </ style > < input type ="button" value ="Add Remove class" onclick =" AddRemoveClass() " /> < div id ="myDiv" class ="myClass">     This is a div </ div > < script type ="text/javascript">     function   AddRemoveClass () {         $( "#myDiv" ).removeClass( "myClass" );         $( "#myDiv" ).addClass( "primary" );         //One liner         $( "#myDiv" ).removeClass( "myClass" ).addClass( "primary" );     } </ script >

Reading / looping through datatable C#

DataTable dt = new DataTable (); dt.Columns.Add( "ID" ); dt.Columns.Add( "Name" ); dt.Columns.Add( "Address" ); DataRow dr = dt.NewRow(); dr[ "ID" ] = 1; dr[ "Name" ] = "John" ; dr[ "Address" ] = "Street 10" ; dt.Rows.Add(dr); DataRow dr1 = dt.NewRow(); dr[ "ID" ] = 2; dr[ "Name" ] = "Smith" ; dr[ "Address" ] = "Street 10" ; dt.Rows.Add(dr1); //Looping through datatable foreach ( DataRow row in dt.Rows) {     Console .WriteLine(row[ "ID" ]);     Console .WriteLine(row[ "Name" ]);     Console .WriteLine(row[ "Address" ]); }

Read ConnnectionString from web.config in C#

ConnectionString is normally stored in web.config and it is recommended to store connectionstring in web.config file. To use connectionstring in our application we need to read connectionstring from web.config. We need to use ConfigurationManager class in order to read connectionstring from web.config . You may need to add reference for assembly “ System.Configuration ” before using ConfigurationManager class. string ConnectionString = ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString; SqlConnection con = new SqlConnection (ConnectionString) ; Web.Config < connectionStrings >     < add name = " DefaultConnection " providerName = " System.Data.SqlClient " connectionString = " YourConnectionStringHere " /> </ connectionStrings >

Apply/change css using jquery

We use css for styling html elemnets but we can use jquery as well to apply different styles to html elements. Jquery has method . css in which we can set different style for html elements. < input type ="button" value ="Change my color" onclick =" ChangeColor() " id ="btnColor" /> < script type ="text/javascript">     function ChangeColor() {         $( "#btnColor" ).css( "color" , "blue" );                //For applying single style         $( "#btnColor" ).css({ "color" : "blue" , "font-size" : "10px" });        //For applying multipl styles     } </ script >

Getting value of textbox using javascript/jquery

Javascript and jquery are commonly used for client side scripting. Here we will see how we can get value of textbox using javascript and jquery. Html < input type ="number" id ="txtAge" /> Using Javascript < script type ="text/javascript">       var age = document.getElementById( "txtAge" ).value; </ script > Jquery < script type ="text/javascript"> var age = $( "#txtAge" ).val(); </ script >

How to call Stored Procedure using C#

Stored Procedures are used to execute a specific set of commands. To use stored procedure in .Net we can use SqlCommand object.  There are properties of SqlCommand which we need to set in order to call stored procedure. First we need to set CommandText property we will assign this property with name of our stored procedure. Then we need to tell CommandType of SqlCommand which will be CommandType .StoredProcedure in case of stored procedure, in case of simple query we will set this to CommandType .Text DataTable dt = new DataTable (); using ( SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString)) {    using ( SqlCommand cmd = new SqlCommand ())    {       using ( SqlDataAdapter adapter = new SqlDataAdapter ())       {          con.Open();          cmd.CommandText = "uspGetAllUsers" ;    //Name of stored procedure          cmd.Connection = con;          cmd.CommandType = CommandType .StoredP

Load data from SqlDataReader into DataTable

SqlDatareader is used in .Net to read data from sql server database. We may have a situation where we need to fill data into DataTable from SqlDataReader . DatatTable has a Load method which accepts SqlDataReader object and fills DataTable with data. DataTable dt = new DataTable (); using ( SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "DefaultConnection" ].ConnectionString)) {    using ( SqlCommand cmd = new SqlCommand ())    {       con.Open();       cmd.CommandText = "Select * from tblUsers" ;       cmd.Connection = con;       cmd.CommandType = CommandType .Text;        SqlDataReader reader = null ;       reader = cmd.ExecuteReader();       dt.Load(reader);                         } }

Send and receive QueryString values in Asp.Net

Querystring is used to transfer information from one page to another. It is the most commonly used way to transfer information between pages. Let’s see how we can send and receive QueryString in ASP.NET . Sending QueryString Response.Redirect( "Home.aspx?UserId=110" ); Receiving QueryString int UserID = 0; if (Request.QueryString[ "UserId" ] != null ) {   int .TryParse(Request.QueryString[ "UserId" ], out UserID); }

Filter DataTable in C#

Datatable is used to store data in table form. We may face a situation where we need to filter datatable in C# code. Here is how we can load data in datatable. Below is a table which we will load in datatable in C#. ID Name Address 1 Mairaj Street 1 2 Ahmad Street 10 3 Minhas Street 12 We will filter the table using the ID column where ID value is 1. DataRow []FilteredData = dt.Select( "ID = 1" ); foreach ( DataRow row in FilteredData) {   Console .WriteLine(FilteredData[0][ "ID" ]); } The result retuned by Select method is an array of DataRow. We can loop through array to get value from each row.

Using Session in ASP.NET

Session is commonly used to store data for per user who is logged in or using website. Common use of Session can be storing username, UserID who is logged in to the website.  Session values can be accessed from any page within the website. Below is the code how we can store and get value from Session. Storing Value in Session Session[ "UserName" ] = "Mairaj Ahmad" ; Getting value from Session string UserName = string .Empty; if (Session[ "UserName" ] != null ) {    UserName = Session[ "UserName" ] as string ; } Session is an Object so we need to convert the session value to the type which we have stored when getting value from session. Here we stored a string value into session so when getting value from session we need to convert the value of session in string .

Converting string to int using TryParse

Datatype int is a very commonly used in .Net applications. We may face a situation where we need to convert string into int. . Net has provided many methods for converting string to int. We will use TryPare method to convert string to int . As TryParse method doesn’t throw exception if string cannot be converted to int. Return value of this method is bool which indicates whether conversion was successful or not . string MarksObtained = "90" ; int Marks = 0; bool Converted = int .TryParse(MarksObtained, out Marks);

Load data in datatable from SQL Server database

Loading data from database is very basic part of every application which uses database as data store. Let's see how we can load data in  DataTable  from database using  ADO.NET  from a  SQL server database. DataTable  dt =  new   DataTable (); using  ( SqlConnection  con =  new   SqlConnection ( ConfigurationManager .ConnectionStrings[ "MyConnectionString" ].ConnectionString)) {     using  ( SqlCommand  cmd =  new   SqlCommand ())    {       cmd.CommandText =  "Select * from tblUsers" ;       cmd.Connection = con;       cmd.CommandType =  CommandType .Text;        using  ( SqlDataAdapter  adapter =  new   SqlDataAdapter (cmd))       {          adapter.Fill(dt);         }     }  }

Load data in datatable from SQL Server database

Loading data from database is very basic part of every application which uses database as data store. Let's see how we can load data in DataTable from database using ADO.NET from a SQL server database. DataTable dt = new DataTable (); using ( SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "MyConnectionString" ].ConnectionString)) {    using ( SqlCommand cmd = new SqlCommand ())    {       cmd.CommandText = "Select * from tblUsers" ;       cmd.Connection = con;       cmd.CommandType = CommandType .Text;       using ( SqlDataAdapter adapter = new SqlDataAdapter (cmd))       {          adapter.Fill(dt);         }     }  }

Filter List of strings by Starting word

List<T> are a very commonly used in C# to store large amount of data. We may need to filter the data contained in a List . Let’s take a List<string> if we need to filter all those items which start from a specific word we can use StartsWith method to get all those items which start with word “A”. List < string > Fruits = new List < string >() { "Apple" , "Mango" , "Orange" , "Apricot" }; var MyFruits = Fruits.FindAll(x => x.StartsWith( "A" )); This will result in following Apple Apricot