OnItemCommand is not fired ListView C#, ASP.NET

I worked in ListView. And i faced one issue with OnItemCommand. There is link button, on click this button OnItemCommand event shoud fire. But it is not working. Because there is no PostBack check in the Page_Load event. By adding IsPostBack, this issue will be resolved.

Aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyListViewTest.aspx.cs" Inherits="IgroupUploader.MyListViewTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:ListView ID="lvFile" runat="server" OnItemCommand="lvFile_ItemCommand" GroupItemCount="2" GroupPlaceholderID="groupPlaceholder">
        <LayoutTemplate>
        <table>
            <tr>
                <td runat="server" id="groupPlaceholder"></td>
            </tr>
          </table>
        </div>
        </LayoutTemplate>

        <GroupTemplate>
            <tr>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
            </tr>
        </GroupTemplate>
        <GroupSeparatorTemplate>
           <tr><td style="height:23px;"></td></tr>
        </GroupSeparatorTemplate>
        <ItemTemplate>
            <td>
                <asp:LinkButton ID="LinkButton1" CommandName="Delete" runat="server" Text='<%#Eval("OriginalFileName")  %>' >LinkButton</asp:LinkButton>
              </td> 
        </ItemTemplate>
    </asp:ListView>
    </div>
    </form>
</body>
</html>

Code Behind:

 protected void Page_Load(object sender, EventArgs e)
        {
                    GetFileList();

        }

 public void GetFileList()
        {
            DataTable dtFile = new DataTable();
            DataAccessLayer ObjData = new DataAccessLayer();

            //Get all the files uploaded by the logged in user.
            dtFile = ObjData.GetAllFiles(UserHashCode, this.IsAdmin);
            //Bind it to the listview.
            lvFile.DataSource = dtFile;
            lvFile.DataBind();
        }

        protected void lvFile_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                
            }
            
        }

Every thing is fine in the front end. We have to add not IsPostBack in the page load:

Working Code

 protected void Page_Load(object sender, EventArgs e)
        {
                     if (!IsPostBack)
            {
                
                    GetFileList();

            }

        }

 public void GetFileList()
        {
            DataTable dtFile = new DataTable();
            DataAccessLayer ObjData = new DataAccessLayer();

            //Get all the files uploaded by the logged in user.
            dtFile = ObjData.GetAllFiles(UserHashCode, this.IsAdmin);
            //Bind it to the listview.
            lvFile.DataSource = dtFile;
            lvFile.DataBind();
        }

        protected void lvFile_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                
            }
            
        }

500 Internal Server Error while calling webmethod from javascript

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

Please down load the project
This is the error due to single quote in your input parameter

I am going to explain this issue with an example:
there are two input fields in my page

1. Name
2. State

Case1 :
put any value except single quote in both the fields and submit. it will work fine.

Case2 :
put single quote in name field and in state field put any value. Open firebug console and check
result:500 Internal Server Error

Problem : The single quote is creating problem.

Solution:Replace all the single quote in the value with a &clubs; and in webmethod again  replace all the &clubs; with single quote.

login.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="CallAjaxWebmethod.login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function SaveDetails()
        {
            var name = $("#txtName").val().trim();
            var state = $("#txtState").val().trim();

            //replacing all the single quotes with &clubs;
            name = name.replace(/'/g, '&clubs;');
            state = state.replace(/'/g, '&clubs;');

            //This is the data i am sending to webmethod
            var dataList = "{ 'Name':'" + name + "','State':'" + state + "'}";

            $.ajax({
                type: "post",
                contentType: "application/json; charset=utf-8",
                url: "login.aspx/SaveDetails",
                data: dataList,
                dataType: "json",
                success: function (data, textStatus) {
                    if (data.d == "true") {
                        alert("success");

                    } else {
                        alert("failed");
                    }
                }
            });
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 100%;">
            <tr>
                <td><span>Name</span></td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td><span>State</span></td>
                <td><input id="txtState" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2"><input id="btnSubmit" type="button" value="Save" onclick="SaveDetails()"/></td>
            </tr>
        </table>

    </div>
    </form>

</body>
</html>

login.aspx.cs

using System;
using System.Web.Script.Services;
using System.Web.Services;

namespace CallAjaxWebmethod
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        [ScriptMethod]
        public static string SaveDetails(string Name,string State)
        {
            try
            {
                //i am replacing the &clubs; with single quote
                Name = Name.Replace("&clubs;", "'");
                State = State.Replace("&clubs;", "'");

                return "true";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

A simple demo Jqgrid

The jqgrid is filled by Ajax enabled webservice.
Steps:
–Add an ASP.NET Web Application. Automatically a project will be added.
–Add a new Web Form to this project and name this page as “gridcontainer.aspx”
–Add A new project and select WCF Service Application to the existing solution. And name this as MyService.
–Add a new WCF Service(Ajax-enabled) service to Myservice project. Automatically it will add a new service having name as Service2.svc
–Add a Global.asax file to this service.
Here is the total project A simple demo Jqgrid
Please download the project and run the Database scripts in for the table and the procedure.
Please insert some records into the table yourself

Service2.svc.cs content:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string GetName()
        {
            // Add your operation implementation here
            return "Sibasis";
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            DataTable table = new DataTable("Company");
            SqlConnection con=null;
            List lstCo = new List();

            try
            {
                using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["sibasis"].ConnectionString))
                {
                    con.Open();
                    using ( SqlCommand cmd = new SqlCommand("GetAllCompany", con))
                    {
                        using ( SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                        {
                            adapter.Fill(table);
                        }
                    }
                }

                foreach (DataRow row in table.Rows)
                {
                    Company cmp = new Company();
                    cmp.Id = Convert.ToInt32(row["ID"]);
                    cmp.Name = Convert.ToString(row["Name"]);
                    cmp.Country = Convert.ToString(row["Country"]);
                    cmp.State = Convert.ToString(row["State"]);
                    cmp.Language = Convert.ToString(row["Language"]);

                    lstCo.Add(cmp);
                }
        }
            catch (Exception ex)
            {
                throw ex;
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

Add the following codes to the Global.asax file in the Myservice project.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Add the following code in the Myservice web.config file

 <endpointBehaviors>
        <behavior name="MyService.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

Then you are ready with the Jqgrid.

Fill JqGrid using Ajax enabled web service.

You can get the project hereindex
If you want to see a demo the go here trirand.com.
Then click on the Searching tab >Toolbar with Operations

This is pretty simple to fill a jqgrid.
1.Create a simple Project with ASP.NET Web application.
2.Add a WCF Service Application to this solution.
3.Make a slightly modification to your web.config in the wcfservice project

   <endpointBehaviors>
        <behavior name="WcfService1.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

4.Add an Web Service(Ajax enabled) in the wcfservice project.
Service2.svc
content goes here

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            // Add your operation implementation here
            List lstCo = new List();
            for (int i = 0; i < 20; i++)
            {
                Company cmp= new  Company();
                cmp.Id=1;
                cmp.Name="test";
                cmp.Country = "test";
                cmp.State = "test";
                cmp.Language = "test";
                lstCo.Add(cmp);
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

2. Add a Global.asax file.
add the following code to Global.asax file

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Then you are ready to go

Row delete + JQGRID

You have to edit in Aspx for the JQgrid defination
Suppose previously you have 4 columns  as following.
colNames: [‘TestimonyID’, ‘Name’, ‘Location’, ‘Approved’]
Now you have to add one new column in defination, now the  colNames will be
colNames: [‘TestimonyID’, ‘Name’, ‘Location’, ‘Approved’,’Delete’]
In colModel you have to add the defination for the Delete column.

<script type="text/javascript">
function deleteClick(Id)
{
       window.location.href = window.location.href + "?deleteid=" + Id;
}

$(function () {
    $("#UsersGrid").jqGrid({
        //Please put your corresponding hanler in place of GrdHandler.ashx
        //I have used handler to fetch data from database.
        url: 'GrdHandler.ashx',
        datatype: 'json',
        height: 250,
        width: 600,
        //Define your columns Here.
        colNames: ['TestimonyID', 'Name', 'Location', 'Approved','Delete'],
        colModel: [
                        { name: 'TestimonyID', index: 'TestimonyID', width: 100, hidden: true, sortable: true, search: true, sorttype: 'integer' },
                        { name: 'Name', index: 'Name', width:200, sortable: true, search: true, sorttype: 'string'},
                        { name: 'Location', index: 'Location', width: 200, sortable: true, search: true, sorttype: 'string' },
                        { name: 'Approved', index: 'Approved', width: 100, sortable: true, search: true, sorttype: 'date' },
                        { name: 'Delete', width: 100, sortable: false, search: false, formatter: function (cellvalue, rowId, rowObject) {
                            var requestName, requestID;
                            if ($.isArray(rowObject)) {
                            //For the first page in grid.
                                // access per array. We are currently in the initial grid filling
                                requestID = rowObject[0];
                            } else {
                                //For the all pages except first page in grid.
                                requestID = rowObject.TestimonyID;
                            }
                            return "<a style="cursor: pointer; text-decoration: underline;" onclick="deleteClick(' + requestID + ')">Delete</a>";
                        }
                        }

                    ],
        rowNum: 10,
        rowList: [10, 20, 30],
        mtype: "GET",
        //This property is very usefull.
        loadonce: true,
        pager: '#UsersGridPager',
        sortname: 'TestimonyID',
        viewrecords: true,
        sortorder: 'asc',
        sortable: true,
        //Change your table name
        caption: 'Testimony Table',
        //Ignore Case while searching
        ignoreCase: true,
        editurl: 'GrdHandler.ashx',
        onPaging: function (b) {
            var nextPg = $(this).getGridParam("page");
            currPg = nextPg;
            return;
        }
    });
    jQuery("#UsersGrid").jqGrid('filterToolbar', { searchOperators: false, searchOnEnter: false, autosearch: true });
});
></script>

In browser the Grid will look like
Delete + Jqgrid
In the code behind get the deleteid from the query string and delete it using your normal code as following

 protected void Page_Load(object sender, EventArgs e)
        {
            int deleteId = 0;

                if (!IsPostBack)
                {
                    //Check the query string deletedId
                    if (int.TryParse(Request.QueryString["deleteid"], out deleteId))
                    {
                        DeleteRecord(deleteId);
                    }
                }

        }
 private void DeleteRecord(int testimonyId)
        {

        }

JQGrid with toolbar Searching, Sorting and Paging functionality with Examples.

Steps to use Jqgrid. (If you will do a single mistake then JQgrid will not work.)

1.Go through the JQGrid Setup Process. Please follow the instruction here
2.Get all the scripts from here
3.Get all the Updated CSS form here

You can get the total code here
Bellow is my folder structure

Folder Structure

Here is my code for GridContainer.aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridContainer.aspx.cs" Inherits="JQGridBind.GridContainer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.8.16.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(function () {
    $("#UsersGrid").jqGrid({
        //Please put your corresponding hanler in place of GrdHandler.ashx
        //I have used handler to fetch data from database.
        url: 'GrdHandler.ashx',
        datatype: 'json',
        height: 250,
        width: 600,
        //Define your columns Here.
        colNames: ['TestimonyID', 'Name', 'Location', 'Approved'],
        colModel: [
                        { name: 'TestimonyID', index: 'TestimonyID', width: 100, hidden: true, sortable: true, search: true, sorttype: 'integer' },
                        { name: 'Name', index: 'Name', width:200, sortable: true, search: true, sorttype: 'string'},
                        { name: 'Location', index: 'Location', width: 200, sortable: true, search: true, sorttype: 'string' },
                        { name: 'Approved', index: 'Approved', width: 100, sortable: true, search: true, sorttype: 'date' }

                    ],
        rowNum: 10,
        rowList: [10, 20, 30],
        mtype: "GET",
        //This property is very usefull.
        loadonce: true,
        pager: '#UsersGridPager',
        sortname: 'TestimonyID',
        viewrecords: true,
        sortorder: 'asc',
        sortable: true,
        //Change your table name
        caption: 'Testimony Table',
        //Ignore Case while searching
        ignoreCase: true,
        editurl: 'GrdHandler.ashx',
        onPaging: function (b) {
            var nextPg = $(this).getGridParam("page");
            currPg = nextPg;
            return;
        }
    });
    jQuery("#UsersGrid").jqGrid('filterToolbar', { searchOperators: false, searchOnEnter: false, autosearch: true });
});

</script>
</head>
<body>
    <form id="HtmlForm" runat="server">
    <table id="UsersGrid" cellpadding="0" cellspacing="0">
    </table>
     <div id="UsersGridPager" style="width:500px">
        </div>
    </form>
</body>
</html>

Here is my code for GrdHandler.ashx handler.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Script.Serialization;

namespace JQGridBind
{
    /// <summary>
    /// Summary description for GrdHandler
    /// </summary>
    public class GrdHandler : IHttpHandler
    {
        public struct JQGridResults
        {
            public int page;
            public int total;
            public int records;
            public JQGridRow[] rows;
        }
        public struct JQGridRow
        {
            public int id;
            public string[] cell;
        }

        [Serializable]
        public class Testimony
        {
            public int TestimonyID { get; set; }
            public string Name { get; set; }
            public string Location { get; set; }
            public string Approved { get; set; }
            public static int totalRecord;
        }

        private Collection<Testimony> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy)
        {
            Collection<Testimony> testimonyCollection = new Collection<Testimony>();
            DataSet ds = new DataSet();
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["whativaluemost"].ConnectionString;
            using (var con = new SqlConnection(connectionString))
            {
                con.Open();
                int start = (Convert.ToInt32(pageIndex) - 1) * Convert.ToInt32(numberOfRows);
                int end = Convert.ToInt32(pageIndex) * Convert.ToInt32(numberOfRows);
                SqlCommand cmd = new SqlCommand();
                SqlDataAdapter SqlDadp = new SqlDataAdapter();
                DataTable dt = new DataTable();
                cmd = new SqlCommand("spLoadAdminTestimonyList", con);
                cmd.Parameters.Add(new SqlParameter("@Search", ""));
                cmd.Parameters.Add(new SqlParameter("@Sort", sortColumnName));
                cmd.Parameters.Add(new SqlParameter("@SortDirc", "ASC"));
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDadp.SelectCommand = cmd;
                SqlDadp.Fill(ds);
            }

            var userDetails = ds.Tables[0];
            Testimony.totalRecord = userDetails.Rows.Count;
            int userCount = userDetails.Rows.Count;
            int i = 0;
            while (i < userCount)
            {
                Testimony testimony = new Testimony();
                testimony.Name = Convert.ToString(userDetails.Rows[i][0]);
                testimony.Location = Convert.ToString(userDetails.Rows[i][1]);
                int TestimonyID = 0;
                if (userDetails.Rows[i][2] != null)
                {
                    int.TryParse(userDetails.Rows[i][2].ToString(), out TestimonyID);
                }
                testimony.TestimonyID = TestimonyID;
                testimony.TestimonyID = (int)userDetails.Rows[i][2];
                testimony.Approved = Convert.ToString(userDetails.Rows[i][3]);
                testimonyCollection.Add(testimony);
                i++;
            }
            return testimonyCollection;
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            string url = request.RawUrl;
            string output = string.Empty;

            string _search = request["_search"];
            string numberOfRows = request["rows"];
            string pageIndex = request["page"];
            string sortColumnName = request["sidx"];
            string sortOrderBy = request["sord"];
            //int totalRecords;
            Collection<Testimony> lstTestimony = GetUsers(numberOfRows, pageIndex, sortColumnName, sortOrderBy);
            output = BuildJQGridResults(lstTestimony, Convert.ToInt32(numberOfRows), Convert.ToInt32(pageIndex));

            response.Write(output);
        }

        private string BuildJQGridResults(Collection<Testimony> lstTestimony, int numberOfRows, int pageIndex)
        {

            JQGridResults result = new JQGridResults();
            List<JQGridRow> rows = new List<JQGridRow>();
            foreach (Testimony testimony in lstTestimony)
            {
                JQGridRow row = new JQGridRow();
                row.id = testimony.TestimonyID;
                row.cell = new string[4];
                row.cell[0] = testimony.TestimonyID.ToString();
                row.cell[1] = testimony.Name;
                row.cell[2] = testimony.Location;
                row.cell[3] = testimony.Approved.ToString();
                rows.Add(row);
            }
            result.rows = rows.ToArray();
            result.page = pageIndex;
            result.total = Testimony.totalRecord / numberOfRows;
            return new JavaScriptSerializer().Serialize(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Switch case and Break

You have to use break/goto ,If there are multiple cases inside switch.
In last case the break statement is optional.

int x=7
switch (x)
{
default:
Response.Write(“Default”) ;
goto case 3;
case 1:
Response.Write(“Case 1”);
break;
case 2:
Response.Write(“Case 2”);
goto case 3;
case 3:
Response.Write(“Case 3”);
break;
}
If you will not write the break statement then the following compile time error will occur.
Please check the image bellow.
Compile error

Check Query string in JAVASCRIPT

i will expalin by taking an example:
“www.abc.com?UserId=4”
Here querystring[0]=UserId and querystring[1]=4

function QueryStringCheck()
{
  var field = 'userId';
  var url = window.location.href;
  if(url.indexOf('?' + field + '=') != -1)
  {    var x = url.split('?');
       if (x.length > 1) 
         {
         var querystring = x[1].split('=');
         alert(querystring[0] + ' is ' + querystring[1]);
         return true;
         }
  }
  else if(url.indexOf('&' + field + '=') != -1)
  {
      return true;
  }
  else
  {
     return false;
  }
}

Convert Date to string

string date = DateTime.Today.Date.ToString("dd/MM/yyyy"); //Result "27/08/2012"
string date = DateTime.Today.Date.ToString("dd_MM_yyyy"); //Result "27_08_2012"
string date =DateTime.Today.Date.ToString("MMMM"); //Result "August"
string date =DateTime.Today.Date.ToString("MMM"); //Result "Aug"

Query String Set and Get

Send Query String:
Response.Redirect("queryto.aspx?id=4");

Get Query String:
It is better to check for null before using the queystring.
if (string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string queryString = Request.QueryString["id"];
}