Friday 25 August 2017

Interview Questions 1

Constructors (C#
When a class or struct is created, its constructor is called. Constructors have the same name as the class or struct, and they usually initialize the data members of the new object.

public class Taxi
{
    public bool isInitialized;
    public Taxi()
    {
        isInitialized = true;
    }
}

class TestTaxi
{
    static void Main()
    {
        Taxi t = new Taxi();
        Console.WriteLine(t.isInitialized);
    }
}

bubbles Event Property


The bubbles event property returns a Boolean value that indicates whether or not the event is a bubbling event.
Event bubbling directs an event to its intended target, it works like this:
  • A button is clicked and the event is directed to the button
  • If an event handler is set for that object, the event is triggered
  • If no event handler is set for that object, the event bubbles up (like a bubble in water) to the objects parent
The event bubbles up from parent to parent until it is handled, or until it reaches the document object.

Syntax

event.bubbles

Example

Example

The following example checks if the triggered event is a bubbling event:
<html>
<head>

<script>
function myFunction(e)
  {
  alert(e.bubbles);
  }
</script>
</head>

<body>

<p onclick="myFunction(event)">Click this paragraph.
An alert box will tell if the
event is a bubbling event.</p>

</body>
</html>

Event Bubbling and Event Propagation: Demo

Answer: The concept of event bubbling was introduced to deal with situations where a single event, such as a mouse click, may be handled by two or more event handlers definedat different levels of the Document Object Model (DOM) hierarchy. If this is the case, the event bubbling process starts by executing the event handler defined for individual elements at the lowest level (e.g. individual hyperlinks, buttons, table cells etc.). From there, the eventbubbles up to the containing elements (e.g. a table or a form with its own event handler), then up to even higher-level elements (e.g. the BODY element of the page). Finally, the event ends up being handled at the highest level in the DOM hierarchy, the document element itself (provided that your document has its own event handler).
The term event propagation is often used as a synonym of event bubbling. However, strictly speaking, event propagation is a wider term: it includes not only event bubbling but also event capturing. Event capturing is the opposite of bubbling (events are handled at higher levels first, then sink down to individual elements at lower levels). Event capturing is supported in fewer browsers and rarely used; notably, Internet Explorer prior to version 9.0 does not support event capturing.
Demo: click any cell in the table and watch the click event bubbling!
Year
Roman Numeral
In plain English this means...
1800
MDCCC
The year eighteen hundred
1900
MCM
The year nineteen hundred
2000
MM
The year two thousand
 [For a full reset, reload the page]
In this demo, onclick event handlers change the background color of their respective elements. The event handlers are defined at four levels: 
(1) the document body 
<BODY onclick="handleBODY()" ...> 
(2) the table element: 
<TABLE id=tb1 onclick="handleTABLE(event,this.id)" ...> 
(3) table row elements: 
<TR id=tr1 onclick="handleTR(event,this.id)"> 
(4) individual table cells: 
<TD id=td11 onclick="handleTD(event,this.id)"> 
When you click inside table cells, event handlers at the lowest level (4) are triggered first, followed by event handlers at higher levels (3), (2), (1), in this order. Each event handler displays an alert message box telling you the level at which the
click event is currently handled. The execution is paused until you dismiss the alert box.

event.stopPropagation()

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
This method does not accept any arguments.


Kill the bubbling on the click event.

1
2
3
4
$("p").click(function(event){
  event.stopPropagation();
  // do something
});  

Javascript error handling with try .. catch .. finally



The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. more

function myFunc() {
     try {
         if (true) {
               throw "An error";
          }
          return true;
     } catch (e) {
          alert (e);
          return false;
     } finally {
          //do cleanup, etc here
     }
 }

event.preventDefault()

Description: If this method is called, the default action of the event will not be triggered.
<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

<script>
$("a").click(function(event) {
  event.preventDefault();
  $('<div/>')
    .append('default ' + event.type + ' prevented')
    .appendTo('#log');
});
</script>

</body>
</html>

JavaScript isNaN() Function

The isNaN() function determines whether a value is an illegal number (Not-a-Number).
This function returns true if the value is NaN, and false if not.
<script>

document.write(isNaN(123)+ "<br>");
document.write(isNaN(-1.23)+ "<br>");
document.write(isNaN(5-2)+ "<br>");
document.write(isNaN(0)+ "<br>");
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2005/12/12")+ "<br>");

</script>

JavaScript Infinity Property

Infinity is a numeric value that represents positive infinity.
-Infinity is a numeric value that represents negative infinity.
Infinity is displayed when a number exceeds the upper limit of the floating point numbers, which is 1.7976931348623157E+10308.
-Infinity is displayed when a number exceeds the lower limit of the floating point numbers, which is -1.7976931348623157E+10308.
<script>

var x=1.7976931348623157E+10308;
document.write(x + "<br>");

var y=-1.7976931348623157E+10308;
document.write(y);

</script>

Infinity
-Infinity
What is the data type of variables of in JavaScript? 
All variables are of object type in JavaScript.
 

In a pop-up browser window, how do you refer to the main browser window that opened it? 
Use window.opener to refer to the main window from pop-ups.

What is === operator ? 
==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

How to get the selected value of dropdownlist using JavaScript?


421
down voteaccepted
If you have a select element that looks like this:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running this code:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Would make strUser be 2. If what you actually want is test2, then do this:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;




paging in gridview in asp.net



protected void grvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
       {
           grvDetails.PageIndex = e.NewPageIndex;
           bindGrid();
       }

JQuery Bind() And Unbind() Example

http://0.gravatar.com/avatar/622c70d2908e68ecc070ca6754245bb2?s=40&d=http%3A%2F%2Fwww.mkyong.com%2Fwp-content%2Fthemes%2Fmkyongnew%2Fimages%2Favatar-guest.jpg%3Fs%3D40&r=G
Posted on May 20, 2010 ,     Last modified : August 30, 2012
By mkyong
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.

Examples

Simple html code for the demonstration.
<div id="BoxId">
        Mouseover Me, Click Me or Double Click Me
</div>
<span></span>

1. bind()

jQuery has full supports of the JavaScript event types such as “click” , “dblclick” or custom event names.
Bind a single click event to elements with an Id of “BoxId”.
$("#BoxId").bind("click", (function () {
        $('span').text("Single Clicked");
}));
Bind a double click event to elements with an Id of “BoxId”.
$("#BoxId").bind("dblclick", (function () {
        $('span').text("Double Clicked");
}));

2. bind() + event object

jQuery comes with many event objects to get more information about the user’s environment, check here for jQuery event object details.
Bind a ‘mouseover’ event with an event object parameter to elements with an Id of “BoxId”.
$("#BoxId").bind("mouseover", (function (event) {
        $('span').text('The mouse cursor is at ('
        + event.pageX + ', ' + event.pageY + ')');
}));

3. bind() + event data

It’s means pass a custom parameter data to your bind() function.
Bind a single click event and pass a custom message as parameter to an elements with an Id of “BoxId”. Inside the function, you can access the parameter message with the help of event.data.
var name = 'Message pass by jQuery event data';
$("#BoxId").bind("click", {msg: name},(function (event) {
        $('span').text("Single Clicked - " + event.data.msg);
}));

4. bind() + Multiple events

To bind a multiple events together, you can include each one separated by a space.
Bind single click and double clicks events to elements with an Id of “BoxId”.
$("#BoxId").bind("click dblclick", (function () {
        $('span').text("Single Clicked");
}));
Alternatively, you can also code like following : (Supported in jQuery 1.4).
$("#BoxId").bind({
        click : function(){
               $('span').text("Single Clicked");
        },
        dblclick : function(){
               $('span').text("Double Clicked");
        }
});

5. unbind()

Unbind or detached the existing events is quite easy, just need to specified the attached event type.
Detached the “click” and “dblclick” event from elements with an Id of “BoxId”.
$('#BoxId').unbind("click");
$('#BoxId').unbind("dblclick");

Try it yourself

<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
 
<style type="text/css">
        .ClassA{
               padding:8px;
               border:1px solid blue;
        }
        span{
               color:#CC6633;
        }
</style>
 
</head>
<body>
  <h1>jQuery bind() and unbind() example</h1>
 
  <div id="BoxId">
        Mouseover Me, Click Me or Double Click Me
  </div>
  <span></span>
  <p>
  <button id="bindButton">bind()</button>
  <button id="bindMessageButton">bind(message)</button>
  <button id="unbindButton">unbind()</button>
  </p>
 
<script type="text/javascript">
 
    $("#BoxId").bind("click", (function () {
               $('span').text("Single Clicked");
    }));
 
    $("#BoxId").bind("dblclick", (function () {
               $('span').text("Double Clicked");
    }));
 
   //Event object
   $("#BoxId").bind("mouseover", (function (event) {
               $('span').text('The mouse cursor is at ('
                 + event.pageX + ', ' + event.pageY + ')');
    }));
 
    //Passing event data
    $("#bindMessageButton").bind("click", (function () {
               var name = 'Message pass by jQuery event data';
               $("#BoxId").bind("click", {msg: name},(function (event) {
                       $('span').text("Single Clicked - " + event.data.msg);
     }));
    }));
 
    $("#unbindButton").bind("click",(function () {
               $('#BoxId').unbind("click");
               $('#BoxId').unbind("dblclick");
               $('#BoxId').unbind("mouseover");
               $('span').text("");
    }));
 
    //added since version 1.4
    $("#bindButton").bind("click",(function () {
 
               $("#BoxId").bind({
                       click : function(){
                               $('span').text("Single Clicked");
                       },
                       dblclick : function(){
                               $('span').text("Double Clicked");
                       },
                       mouseover : function(event){
                               $('span').text('The mouse cursor is at ('
                                + event.pageX + ', ' + event.pageY + ')');
                       }
               });
    }));
 
</script>
</body>
</html>

How IIS Process ASP.NET Request

Introduction
When request come from client to the server a lot of operation is performed before sending response to the client. This is all about how IIS Process the request.  Here I am not going to describe the Page Life Cycle and there events, this article is all about the operation of IIS Level.  Before we start with the actual details, let’s start from the beginning so that each and everyone understand it's details easily.  Please provide your valuable feedback and suggestion to improve this article.


What is Web Server ?
When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine is responsible to execute all kind of asp.net requests and responses.  The process name is "WebDev.WebServer.Exe" which actually takw care of all request and response of an web application which is running from Visual Studio IDE.
Now, the name “Web Server” come into picture when we want to host the application on a centralized location and wanted to access from many locations. Web server is responsible for handle all the requests that are coming from clients, process them and provide the responses.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500763171406_Firstone.JPG
What is IIS ?
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine  to handle the ASP.NET request. So, when a request comes from client to server, IIS takes that request and  process it and send response back to clients.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501029987812_IISProcessRequest.JPG
Request Processing :

Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now let’s have a look how they do things internally. Before we move ahead, you have to know about two main concepts
1.    Worker Process
2.   
 Application Pool

Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.

Application Pool:  Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn't not impact other web application as they they are configured into different application pools.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500651403828_AppPool.JPG

Application Pool with multiple worker process is called
 “Web Garden”.

Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now let’s have look how IIS process the request when a new request comes up from client.

If we look into the IIS 6.0 Architecture, we can divided them into Two Layer

1.   
 Kernel Mode
2.   
 User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS.  So whenever a request comes from Client to Server, it will hit HTTP.SYS First.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500723005391_BasicLevel.JPG

Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one question, How HTTP.SYS comes to know where to send the request?  This is not a random pickup. Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request. 
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501112380391_RegisterApp.JPG

So, this was the first steps of IIS Request Processing.

Till now, Client Requested for some information and request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.
 
In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to the respective application pool.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501155671406_Was.JPG

When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the mapping into IIS.   

Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with IIS using aspnet_regiis command.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501195202656_WithAll.JPG

When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls theProcessRequest method to start Processing.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041501078679219_ProcessRequest.JPG


When this methods called, a new instance of HTTPContext is been created.  Which is accessible using HTTPContext.Current  Properties. This object still remains alive during life time of object request.  Using HttpContext.Current we can access some other objects like Request, Response, Session etc. 

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500806755391_HttpContext.JPG
After that HttpRuntime load an HttpApplication object with the help of  HttpApplicationFactory class.. Each and every request should pass through the corresponding HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.

Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We can also create our own HTTPModule if we need to handle anything during upcoming request and response.

http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500917175312_httppipleline.JPG
HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the HTTPModule should reached to HTTPHandler.  Then  HTTP Handler  generates the output for the requested resource. So, when we requesting for any aspx web pages,   it returns the corresponding HTML output.
All the request now passes from  httpModule to  respective HTTPHandler then method and the ASP.NET Page life cycle starts.  This ends the IIS Request processing and start the ASP.NET Page Lifecycle.
http://www.dotnetfunda.com/UserFiles/ArticlesFiles/Abhijit%20Jana_634041500577575703_allStep.JPG
Conclusion
When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective  Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.
This was just overview of IIS Request Processing to let Beginner’s know how the request get processed in backend.  If you want to learn in details please check the link for Reference and further Study section.

what is the use of static variable in c#?When to use it?why cant i declare the static variable inside Method?


Finally i understand the static variable.....static variable shared the value of it among all instances of the class.
Example without declaring it static
public  class Variable
{
    public int i = 5;
    public void test()
    {
        i=i+5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}
Explanation:If you look at the above example i just declare int variable.when i run this code the output will be 10 and 10.Its simple
Now Lets Look at the static variable Here,I am declaring the variable as a static.
Example with static variable
public  class Variable
{
    public static int i = 5;
    public void test()
    {
        i=i+5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}
Now when i run above code then the output will be 10 and 15.so static variable value shared among all instances of that class.

system.array can have a different data type

1.If we specified a type when declaring an array then we can't use multiple datatype for that array.

take a example ->

        int[] arr = new int[5];
        arr[0] = 9;
        arr[1] = 45;
        arr[2] = "66";

Then it gives Error as -> "Cannot implicitly convert type 'string' to 'int'";

2.If you want to store multiple datatypes value in an array then declare your array as Object.Then you can use multiple data types values.

take a example ->

   object[] arr = new object[8];
        arr[0] = 45;
        arr[1] = "77";
        arr[2] = 78;

so by declaring array as object then it can have multiple data types value.

difference between static and sealed class in .NET

Sealed classes: 
1)Can create instances, but cannot inherit
2)Can contain static as well as nonstatic members.

Static classes:
1)Can neither create their instances, nor inherit them
2)Can have static members only.

How can we inherit a static member?

When inheriting static members there is no need to instantiate the
defining class using the ‘new’ keyword.
public class MyBaseClass
{
MyBaseClass()
{
}
public static void PrintName()
{
}
}
public class MyDerivedClass : MyBaseClass
{
MyDerivedClass ()
{
}
public void DoSomething()
{
MyBaseClass.GetName();
}
}


Web browser limits for cookies?

 Cookie size is limited to 4096 bytes. It is not much, so cookies are
used to store small amounts of data,
often just user id.
- Also, number of cookies is limited to 20 per website. If you make
new cookie when you already have 20
cookies, browser will delete oldest one.
- Your web site visitor can change browser settings to not accept
cookies. In that case you are not able to
save and retrieve data on this way! Because of this, it is good to
check browser settings before saving a
cookie.
- If your visitor blocked cookies in web browser privacy settings, you
need to decide do you still want to
save that data on some other way (maybe with sessions) or to not save
it at all. Anyway, your application
must continue to work normally with any browser privacy settings. It
is better to not store any sensitive or
critical data to cookies. If using of cookies is necessary, you should
inform your users with some message
like: “Cookies must be enabled to use this application”.

Explain Cookies in .Net?

Cookie are one of several ways to store data about web site visitors
during the time when web server and
browser are not connected. Common use of cookies is to remember users
between visits. Practically, cookie
is a small text file sent by web server and saved by web browser on
client machine.
C#
// Add this on the beginning of your .vb code file
using System;
// Use this line when you want to save a cookie
Response.Cookies["MyCookieName"].Value = “MyCookieValue”;
// How long will cookie exist on client hard disk
Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);
// To add multiple key/value pairs in single cookie
Response.Cookies["VisitorData"]["FirstName"] = “Richard”;
Response.Cookies["VisitorData"]["LastVisit"] = DateTime.Now.ToString();

Web Server and ASP.NET Application Life Cycle in Depth


Reference Type And Value Type in C#

Introduction

This article will give you a clear insight on what happens when a reference type is passed by value and what would happen when it is passed by reference.

Before diving into the deep sea of C#, I would like to touch the basics of reference and value types.

Reference Types: Always allocated from the managed heap.

Always represented in boxed form.

When we assign a value type to another value type, a field-by-field copy is made.

Value Types: Allocated on thread's stack

Have two form representations "boxed" and "unboxed"

When we copy a reference type to another reference type, only the memory address is copied.

Practical Time!!

Write down the following code and try guessing the output without running the program:

class Program
{
    
static void Main(string[] args)
    {
        
// Pass reference type by value
        ArrayList arrayList = new ArrayList() { 0, 1, 2, 3 };
         Console.WriteLine("Pass by Value");

        PassByValue(arrayList);
        // What should be the output of below line ??
        Console.WriteLine(arrayList[1]);
                arrayList = 
new ArrayList() { 0, 1, 2, 3 };
             Console.WriteLine("Pass by Reference");
        PassByReference(ref arrayList);
        // What should be the output of below line ??
        Console.WriteLine(arrayList[1]);
        Console.Read();
    }
    private static void PassByValue(ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        
// Now Change the first position value
        arrayList[1] = 90;
        arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
    private static void PassByReference(ref ArrayList arrayList)
    {
        Console.WriteLine(arrayList[1]);
        // Now Change the first position value
        arrayList[1] = 90;
             arrayList = 
new ArrayList() { 101, 102, 103, 104 };
        Console.WriteLine(arrayList[1]);
    }
}

Interpretation

First we'll take the case of passing value types by reference.

Let's have a look at the PassbyValue function:

The first line of code obviously would look out for value placed at second index in the arrayList and print out 1. After that, we change the value present at second index to 90. In the third line, since we had passed the reference type by value; it created a copy of original memory block pointing to the original memory location. But as soon we re-create the object, this loses the reference to the original memory location and acts as a different arrayList object then onwards. However, the changes done to the arrayList before the re-creation of object still persists. That's why, when we try to access the second index value, after the PassByValue function, we still get the output as 90.

Now, let's have a look at the Pass by Reference function:

Here too the first line of code output would be the same as reflected by the PassByValue function. The second would again change the value present at the second index to 90. In the third line, since we had passed the reference type by reference, it would just re-initialize its value to the new array (note that here the original memory location is getting new values overwritten here), thus the value for arrayList[1] inside the function would be 102 and after that the newly changed array would be referred everywhere, even outside the function.

Output

Reference

Conclusion

Passing reference types by Value creates a copy of the memory location and thus it is possible to change the value of the original reference type object inside the function (as soon we re-create that object). Passing reference types by ref doesn't create any copy of the object; it impacts the original reference object.




-------------------------------------------


The following C# source code manually creates a DataGridView columns and rows and hide the second column and second row.
dataGridView1.Rows[Index].Visible = false;
dataGridView1.Columns[Index].Visible = false;


C# DataGridView Sorting and Filtering

The following C# program shows how to filter and sort a DataGridView by using a DataView.
dv = new DataView(ds.Tables[0], "Price > 19", "Price Desc", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;

C# DataGridView Read Only Columns and Rows

You can set ReadOnly Property in three levels. You can make entire dataGridView or entire column or entire row as ReadOnly .
dataGridView1.ReadOnly = true;
dataGridView1.Rows[index].ReadOnly = true;
dataGridView1.Columns[index].ReadOnly = true;





Below are very short scripts that will give you some basic information
/* ================================
Impersonate yourself as other user.
===================================*/
Execute as login = ‘new_login_name’ –
or
Execute as user = ‘new_login_name’
–Example:
select suser_sname()
Execute as login = ‘new_login_name’
select suser_sname()
revert — brings back to your original login/user.
/* ================================
Get the list of all databases
================================ */
select * from sys.databases — SQL Server 2005
Select * from sysdatabases — SQL Server 2000
–Tip:When you are in SQL Server Management Studio or Query Analyzer, Press Ctrl + U, it will activate drop down will all user defined databases.
/* ================================
Get Current Database Name
================================ */
Select Db_Name()
/* ================================
Get list of database files for a specific database
================================ */
Select * from sys.sysfiles — sql server 2005
or
select * from sysfiles — sql server 2000
/* ================================
Get the list of all logins in a server
================================ */
Select * from syslogins — sql server 2005
or
select * from sysxlogins — sql server 2000
/* ================================
Get Current logged in login Name
================================ */
Select suser_sname()
/* ================================
Get the list of all users in a database
================================ */
Select * from Sysusers — sql server 2000
Select * from sys.Sysusers — SQL Server 2005
/* ================================
Get Current logged in User Name
================================*/
Select user_name()
/* ====================================
Get a list of all objects in a database
=======================================*/
Select * from sysobjects — sql server 2000
or
Select * from sys.all_objects — SQL Server 2005
/* ================================
Get list of all user defined tables.
=====================================*/
Select * from information_schema.tables
or
Select * from sys.tables — SQL Server 2005
/* ================================
To get list of all views
================================*/
Select * from sys.views order by create_Date desc — SQL Server 2005
/* ================================
To get list of all procedures,
================================*/
Select * from sys.procedures order by create_Date desc — SQL Server 2005
/*================================
To get list of columns
================================*/
Select * from Information_Schema.columns
/*================================================================
Get the definition (Original text) of procedure, view, function.
================================*================================*/
Exec Sp_Helptext Object_Name
or
Exec Sp_Helptext [owner.objectname]
/*================================================================================================
Get Table ,View structure, information about indexes, constraints, data type, data length.
================================================================================================*/
Exec Sp_Help object_name
or
Exec Sp_Help [owner.object_name]
/*================================================================
Get all dependency on a particular object.
================================================================*/
Sp_depends object_name
/*================================================================
Get list of orphaned (sql server) users.
================================================================*/
Sp_change_users_login ‘report’ :
/* ================================================================
Get Object Level Permision for each user or db_role
================================================================*/
sp_helprotect
or
sp_helprotect @user_name = ‘name of the user’


GridViewRow.RowType Property

Use the RowType property to determine the type of row that the GridViewRow object represents. The following table lists the different row type values using theDataControlRowType enumeration.
Row type
Description
A data row in the GridView control.
The footer row in the GridView control.
The header row in the GridView control.
The empty row in the GridView control. The empty row is displayed when GridView control does not have any records to display.
A pager row in the GridView control.
A separator row in the GridView control.
This property is commonly used to determine a row's type before performing an 



DataKeyNames

One of the Important property of all the Data presentation controls in ASP.Net is the "DataKeynames" This is available in all of the data controls like GridView, DetailsView....etc. Most of the time we will assign the primary key of the data to this property . We can assign more that one data column value to this field, separated by a comma.Thisproperty need to be important at the time of updating a record from the data control.Now we can look one sample on how this datakeyNames were used in a DataGridView


Multiple DataKeyNames

Here If we want to to pass more than on field (for example we want to get the DepartmentID) then the theDataKeyNames will write like this
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="emp_id,dept_id">
 <Columns>
     <asp:BoundField DataField="fname" HeaderText="First name" SortExpression="fname" />
     <asp:BoundField DataField="lname" HeaderText="Last name" SortExpression="lname" />
     <asp:BoundField DataField="hire_date" HeaderText="Hire date" SortExpression="hire_date" />
     <asp:TemplateField HeaderText="Select">
         <ItemTemplate>
             <asp:CheckBox ID="CheckBox1" runat="server" />
         </ItemTemplate>
     </asp:TemplateField>
 </Columns>
</asp:GridView>
And in the Button1_Click event
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
protected void Button1_Click(object sender, EventArgs e)
{
 
foreach (GridViewRow row in GridView1.Rows)
{
  if (((CheckBox)row.FindControl("CheckBox1")).Checked)
  {
 
      int EmployeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
      int DepartementID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[1]);
 
 
  }
}
}




SQL SERVER – Creating Comma Separate Values List from Table – UDF – SP

Following script will create common separate values (CSV) or common separate list from tables. convert list to table. Following script is written for SQL SERVER 2005. It will also work well with very big TEXT field. If you want to use this on SQL SERVER 2000 replace VARCHAR(MAX) with VARCHAR(8000) or any other varchar limit. It will work with INT as well as VARCHAR.
There are three ways to do this. 1) Using COALESCE 2) Using SELECT Smartly 3) Using CURSOR.
The table is example is:
TableName: NumberTable
NumberCols
first
second
third
fourth
fifth
Output : first,second,third,fourth,fifth

Option 1: This is the smartest way.
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + NumberCols
FROM NumberTable
SELECT @listStr
Please make a note that COALESCE returns the first NOT NULL value from the argument list we pass.
Option 2: This is the smart but not the best way; though I have seen similar code many times.
DECLARE @listStr VARCHAR(MAX)
SET @listStr = ''
SELECT @listStr = @listStr + NumberCols + ','
FROM NumberTable
SELECT SUBSTRING(@listStr , 1, LEN(@listStr)-1)
I sometime use ISNULL(NumberCols,’NullValue’) to convert NULL values to other desired value.
Option 3: Cursor are not the best way, please use either of above options.
Above script can be converted to User Defined Function (UDF) or Storped Procedure (SP).

 


No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0