Saturday, August 2, 2008

.Net Interview Questions with answers

Asp.NET 2.0 Job Interview Questions (Part 1)

1. What are the new Data Controls in Asp.net 2.0?
Data access in ASP.NET 2.0 can be accomplished completely declaratively (no code) using the new data-bound and data source controls. There are new data source controls to represent different data backends such as SQL database, business objects, and XML, and there are new data-bound controls for rendering common UI for data, such as gridview, detailsview, and formview.
2. What are the new Navigation Controls in Asp.net 2.0?
The navigation controls provide common UI for navigating between pages in your site, such as treeview, menu, and sitemappath. These controls use the site navigation service in ASP.NET 2.0 to retrieve the custom structure you have defined for your site.
3. What are the new Login Controlsin Asp.net 2.0?
The new login controls provide the building blocks to add authentication and authorization-based UI to your site, such as login forms, create user forms, password retrieval, and custom UI for logged in users or roles. These controls use the built-in membership and role services in ASP.NET 2.0 to interact with the user and role information defined for your site.
4. What are the new Web Part Controls in Asp.net 2.0 ?
Web parts are an exciting new family of controls that enable you to add rich, personalized content and layout to your site, as well as the ability to edit that content and layout directly from your application pages. These controls rely on the personalization services in ASP.NET 2.0 to provide a unique experience for each user in your application.
5. What are Master Pages?
This feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. In one simple place you can control the look, feel, and much of functionality for an entire Web site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.
6. What are Themes and Skins in 2.0, explain usgae scenario?
The themes and skins features in ASP.NET 2.0 allow for easy customization of your site's look-and-feel. You can define style information in a common location called a "theme", and apply that style information globally to pages or controls in your site. Like Master Pages, this improves the maintainability of your site and avoid unnecessary duplication of code for shared styles.
7. What is a profile object, why is it used?
Using the new personalization services in ASP.NET 2.0 you can easily create customized experiences within Web applications. The Profile object enables developers to easily build strongly-typed, sticky data stores for user accounts and build highly customized, relationship based experiences. At the same time, a developer can leverage Web Parts and the personalization service to enable Web site visitors to completely control the layout and behavior of the site, with the knowledge that the site is completely customized for them. Personalizaton scenarios are now easier to build than ever before and require significantly less code and effort to implement.
8. What is Configuration API?
ASP.NET 2.0 contains new configuration management APIs, enabling users to programmatically build programs or scripts that create, read, and update Web.config and machine.config configuration files.
9. What is MMC Admin Tool?
ASP.NET 2.0 provides a new comprehensive admin tool that plugs into the existing IIS Administration MMC, enabling an administrator to graphically read or change common settings within our XML configuration files.
10. Explain the use of Pre-compilation Tool?
ASP.NET 2.0 delivers a new application deployment utility that enables both developers and administrators to precompile a dynamic ASP.NET application prior to deployment. This precompilation automatically identifies any compilation issues anywhere within the site, as well as enables ASP.NET applications to be deployed without any source being stored on the server (one can optionally remove the content of .aspx files as part of the compile phase), further protecting your intellectual property.
11. How is application management and maintenance improved in Asp.net 2.0?
ASP.NET 2.0 also provides new health-monitoring support to enable administrators to be automatically notified when an application on a server starts to experience problems. New tracing features will enable administrators to capture run-time and request data from a production server to better diagnose issues. ASP.NET 2.0 is delivering features that will enable developers and administrators to simplify the day-to-day management and maintenance of their Web applications.
12. What are Provider-driven Application Services? explain in detail?
ASP.NET 2.0 now includes built-in support for membership (user name/password credential storage) and role management services out of the box. The new personalization service enables quick storage/retrieval of user settings and preferences, facilitating rich customization with minimal code. The new site navigation system enables developers to quickly build link structures consistently across a site. As all of these services are provider-driven, they can be easily swapped out and replaced with your own custom implementation. With this extensibility option, you have complete control over the data store and schema that drives these rich application services.
13. Explain Server Control Extensibility with reference to Asp.net 2.0 ?
ASP.NET 2.0 includes improved support for control extensibility, such as more base classes that encapsulate common behaviors, improved designer support, more APIs for interacting with client-side script, metadata-driven support for new features like themes and accessibility verification, better state management, and more.
14. What are the Data Source Controls?
Data access in ASP.NET 2.0 is now performed declaratively using data source controls on a page. In this model, support for new data backend storage providers can be easily added by implementing custom data source controls. Additionally, the SqlDataSource control that ships in the box has built-in support for any ADO.NET managed provider that implements the new provider factory model in ADO.NET.
15. What are Compilation Build Providers?
Dynamic compilation in ASP.NET 2.0 is now handled by extensible compilation build providers, which associate a particular file extension with a handler that knows how to compile that extension dynamically at runtime. For example, .resx files can be dynamically compiled to resources, .wsdl files to web service proxies, and .xsd files to typed DataSet objects. In addition to the built-in support, it is easy to add support for additional extensions by implementing a custom build provider and registering it in Web.config.
16. What is Expression Builders, why would you use it?
ASP.NET 2.0 introduces a declarative new syntax for referencing code to substitute values into the page, called Expression Builders. ASP.NET 2.0 includes expression builders for referencing string resources for localization, connection strings, application settings, and profile values. You can also write your own expression builders to create your own custom syntax to substitute values in a page rendering.
17. Is ASP.NET 64-Bit enabled? how?
ASP.NET 2.0 is now 64-bit enabled, meaning it can take advantage of the full memory address space of new 64-bit processors and servers. Developers can simply copy existing 32-bit ASP.NET applications onto a 64-bit ASP.NET 2.0 server and have them automatically be JIT compiled and executed as native 64-bit applications (no source code changes or manual re-compile are required).
18. Explain how Caching in Asp.net 2.0 is different from Caching in Asp.net 1.1?
ASP.NET 2.0 also now includes automatic database server cache invalidation. This powerful and easy-to-use feature allows developers to aggressively output cache database-driven page and partial page content within a site and have ASP.NET automatically invalidate these cache entries and refresh the content whenever the back-end database changes. Developers can now safely cache time-critical content for long periods without worrying about serving visitors stale data.

















1. What do I need to create and run an ASP.NET application?
• Windows 2000, Windows Server 2003 or Windows XP.
• ASP.NET, which can be either the redistributable (included in the .NET SDK) or Visual Studio .NET.
1. Where can I download the .NET SDK?
.NET SDK can be obtained here.
(You have to install the Microsoft .NET Framework Version 1.1 Redistributable Package before installing the .NET SDK.)
2. Are there any free IDEs for the .NET SDK?
o Microsoft provides Visual Studio 2005 Express Edition Beta for free. Of particular interest to the ASP.NET developers would be the Visual Web Developer 2005 Express Edition Beta 2 available as a free download.
o The ASP.NET Web Matrix Project (supported by Microsoft) is a free IDE for developing ASP.NET applications and is available here.
o There is also a free open-source UNIX version of the Microsoft .NET development platform called Mono available for download here.
o Another increasingly popular Open Source Development Environment for .NET is the #develop (short for SharpDevelop) available for download here.
3. When was ASP.NET released?
ASP.NET is a part of the .NET framework which was released as a software platform in 2002.
4. Is a new version coming up?
ASP.NET 2.0, Visual Studio 2005 (Whidbey), Visual Web Developer 2005 Express Edition are the next releases of Microsoft's Web platform and tools. They have already been released as Beta versions. They are scheduled to be released in the week of November 7, 2005.
5. Explain Namespace.
Namespaces are logical groupings of names used within a program. There may be multiple namespaces in a single application code, grouped based on the identifiers’ use. The name of any given identifier must appear only once in its namespace.
6. List the types of Authentication supported by ASP.NET.
o Windows (default)
o Forms
o Passport
o None (Security disabled)
7. What is CLR?
Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code and provides services like memory management, debugging, security, etc. The CLR is also known as Virtual Execution System (VES).
8. What is CLI?
The CLI is a set of specifications for a runtime environment, including a common type system, base class library, and a machine-independent intermediate code known as the Common Intermediate Language (CIL). (Source: Wikipedia.)
9. List the various stages of Page-Load lifecycle.
o Init()
o Load()
o PreRender()
o Unload()
10. Explain Assembly and Manifest.
An assembly is a collection of one or more files and one of them (DLL or EXE) contains a special metadata called Assembly Manifest. The manifest is stored as binary data and contains details like versioning requirements for the assembly, the author, security permissions, and list of files forming the assembly. An assembly is created whenever a DLL is built. The manifest can be viewed programmatically by making use of classes from the System.Reflection namespace. The tool Intermediate Language Disassembler (ILDASM) can be used for this purpose. It can be launched from the command prompt or via Start> Run.
11. What is Shadow Copy?
In order to replace a COM component on a live web server, it was necessary to stop the entire website, copy the new files and then restart the website. This is not feasible for the web servers that need to be always running. .NET components are different. They can be overwritten at any time using a mechanism called Shadow Copy. It prevents the Portable Executable (PE) files like DLLs and EXEs from being locked. Whenever new versions of the PEs are released, they are automatically detected by the CLR and the changed components will be automatically loaded. They will be used to process all new requests not currently executing, while the older version still runs the currently executing requests. By bleeding out the older version, the update is completed.
12. What is DLL Hell?
DLL hell is the problem that occurs when an installation of a newer application might break or hinder other applications as newer DLLs are copied into the system and the older applications do not support or are not compatible with them. .NET overcomes this problem by supporting multiple versions of an assembly at any given time. This is also called side-by-side component versioning.
13. Explain Web Services.
Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension.
14. Explain Windows Forms.
Windows Forms is employed for developing Windows GUI applications. It is a class library that gives developers access to Windows Common Controls with rich functionality. It is a common GUI library for all the languages supported by the .NET Framework.
15. What is Postback?
When an action occurs (like button click), the page containing all the controls within the tag performs an HTTP POST, while having itself as the target URL. This is called Postback.
16. Explain the differences between server-side and client-side code?
Server side scripting means that all the script will be executed by the server and interpreted as needed. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Since the code is included in the HTML page, anyone can see the code by viewing the page source. It also poses as a possible security hazard for the client computer.
17. Enumerate the types of Directives.
o @ Page directive
o @ Import directive
o @ Implements directive
o @ Register directive
o @ Assembly directive
o @ OutputCache directive
o @ Reference directive
18. What is Code-Behind?
Code-Behind is a concept where the contents of a page are in one file and the server-side code is in another. This allows different people to work on the same page at the same time and also allows either part of the page to be easily redesigned, with no changes required in the other. An Inherits attribute is added to the @ Page directive to specify the location of the Code-Behind file to the ASP.NET page.
19. Describe the difference between inline and code behind.
Inline code is written along side the HTML in a page. There is no separate distinction between design code and logic code. Code-behind is code written in a separate file and referenced by the .aspx page.
20. List the ASP.NET validation controls?
o RequiredFieldValidator
o RangeValidator
o CompareValidator
o RegularExpressionValidator
o CustomValidator
o ValidationSummary
21. What is Data Binding?
Data binding is a way used to connect values from a collection of data (e.g. DataSet) to the controls on a web form. The values from the dataset are automatically displayed in the controls without having to write separate code to display them.
22. Describe Paging in ASP.NET.
The DataGrid control in ASP.NET enables easy paging of the data. The AllowPaging property of the DataGrid can be set to True to perform paging. ASP.NET automatically performs paging and provides the hyperlinks to the other pages in different styles, based on the property that has been set for PagerStyle.Mode.
23. Should user input data validation occur server-side or client-side? Why?
All user input data validation should occur on the server and minimally on the client-side, though it is a good way to reduce server load and network traffic because we can ensure that only data of the appropriate type is submitted from the form. It is totally insecure. The user can view the code used for validation and create a workaround for it. Secondly, the URL of the page that handles the data is freely visible in the original form page. This will allow unscrupulous users to send data from their own forms to your application. Client-side validation can sometimes be performed where deemed appropriate and feasible to provide a richer, more responsive experience for the user.
24. What is the difference between Server.Transfer and Response.Redirect?
o Response.Redirect: This tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser. This results in two requests by the browser.
o Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content. The benefit of this approach is one less round trip to the server from the client browser. Also, any posted form variables and query string parameters are available to the second page as well.


26. What is an interface and what is an abstract class?
In an interface, all methods must be abstract (must not be defined). In an abstract class, some methods can be defined. In an interface, no accessibility modifiers are allowed, whereas it is allowed in abstract classes.
27. Session state vs. View state:
In some cases, using view state is not feasible. The alternative for view state is session state. Session state is employed under the following situations:
o Large amounts of data - View state tends to increase the size of both the HTML page sent to the browser and the size of form posted back. Hence session state is used.
o Secure data - Though the view state data is encoded and may be encrypted, it is better and secure if no sensitive data is sent to the client. Thus, session state is a more secure option.
o Problems in serializing of objects into view state - View state is efficient for a small set of data. Other types like DataSet are slower and can generate a very large view state.
28. Can two different programming languages be mixed in a single ASPX file?
ASP.NET’s built-in parsers are used to remove code from ASPX files and create temporary files. Each parser understands only one language. Therefore mixing of languages in a single ASPX file is not possible.
29. Is it possible to see the code that ASP.NET generates from an ASPX file?
By enabling debugging using a <%@ Page Debug="true" %> directive in the ASPX file or a statement in Web.config, the generated code can be viewed. The code is stored in a CS or VB file (usually in the \%SystemRoot%\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files).
30. Can a custom .NET data type be used in a Web form?
This can be achieved by placing the DLL containing the custom data type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced.
31. List the event handlers that can be included in Global.asax?
o Application start and end event handlers
o Session start and end event handlers
o Per-request event handlers
o Non-deterministic event handlers
32. Can the view state be protected from tampering?
This can be achieved by including an @ Page directive with an EnableViewStateMac="true" attribute in each ASPX file that has to be protected. Another way is to include the statement in the Web.config file.
33. Can the view state be encrypted?
The view state can be encrypted by setting EnableViewStateMac to true and either modifying the element in Machine.config to tag. Then, a byte[] can be declared to read in the data from the input file. This can then be sent to the server.
41. How do I create an ASPX page that periodically refreshes itself?
The following META tag can be used as a trigger to automatically refresh the page every n seconds:

42. How do I initialize a TextBox whose TextMode is "password", with a password?
The TextBox’s Text property cannot be used to assign a value to a password field. Instead, its Value field can be used for that purpose.
ID="Password" RunAt="server" />
43. Why does the control's PostedFile property always show null when using HtmlInputFile control to upload files to a Web server?
This occurs when an enctype="multipart/form-data" attribute is missing in the
tag.
44. How can the focus be set to a specific control when a Web form loads?
This can be achieved by using client-side script:
document.forms[0].TextBox1.focus ()
The above code will set the focus to a TextBox named TextBox1 when the page loads.
45. How does System.Web.UI.Page's IsPostBack property work?
IsPostBack checks to see whether the HTTP request is accompanied by postback data containing a __VIEWSTATE or __EVENTTARGET parameter. If there are none, then it is not a postback.
46. What is WSDL?
WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. The operations and messages are described abstractly, and then bound to a concrete network protocol and message format to define an endpoint. Related concrete endpoints are combined into abstract endpoints (services). (Source: www.w3.org)
47. What is UDDI?
UDDI stands for Universal Description, Discovery, and Integration. It is like an "Yellow Pages" for Web Services. It is maintained by Microsoft, IBM, and Ariba, and is designed to provide detailed information regarding registered Web Services for all vendors. The UDDI can be queried for specific Web Services.
48. Is it possible to generate the source code for an ASP.NET Web service from a WSDL?
The Wsdl.exe tool (.NET Framework SDK) can be used to generate source code for an ASP.NET web service with its WSDL link.
Example: wsdl /server http://api.google.com/GoogleSearch.wsdl.
49. Why do uploads fail while using an ASP.NET file upload control to upload large files?
ASP.NET limits the size of file uploads for security purposes. The default size is 4 MB. This can be changed by modifying the maxRequestLength attribute of Machine.config's element.
50. Describe the difference between inline and code behind.
Inline code is written along side the HTML in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
51. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.
52. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Valid answers are:
o A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
o A DataSet is designed to work without any continuing connection to the original data source.
o Data in a DataSet is bulk-loaded, rather than being loaded on demand.
o There's no concept of cursor types in a DataSet.
o DataSets have no current record pointer You can use For Each loops to move through the data.
o You can store many edits in a DataSet, and write them to the original data source in a single operation.
o Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
53. What’s a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
54. What data types do the RangeValidator control support?
Integer, String, and Date.
55. Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.
56. What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.
57. What is ViewState?
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.
58. What does the "EnableViewState" property do? Why would I want it on or off?
It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.
59. What are the different types of Session state management options available with ASP.NET?
ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.
60. Differences Between XML and HTML?
Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below
XML HTML
User definable tags Defined set of tags designed for web display
Content driven Format driven
End tags required for well formed documents End tags not required
Quotes required around attributes values Quotes not required
Slash required in empty tags Slash not required
61. Give a few examples of types of applications that can benefit from using XML.
There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.
62. What is DOM and how does it relate to XML?
The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.
63. What is SOAP and how does it relate to XML?
The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.
64. Can you walk us through the steps necessary to parse XML documents?
Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response.
65. What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
66. What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.
67. What’s a proxy of the server object in .NET Remoting?
It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
68. What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
69. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
70. What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
71. What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
72. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
73. What’s SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
74. What’s Singleton activation mode?
A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
75. How do you define the lease of the object?
By implementing ILease interface when writing the class code.
76. Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
77. How can you automatically generate interface for the remotable object in .NET with Microsoft tools?
Use the Soapsuds tool.
















1.1 Why are Server control tags shown in the browser instead of the controls it represents?


This is because the server control tags were not converted into their respecting HTML element tags by ASP.Net. This happens when ASP.Net is not properly registered with IIS.
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe
use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.
use the command: aspnet_regiis.exe -i ---> to install current asp.net version.

1.2 How To Repair ASP.Net IIS Mapping After You Remove and Reinstall IIS?


To reassociate aspx file extensions with ASP.Net runtime, you'll have to run the utlity aspnet_regiis.exe -i
For more information refer to Microsoft Knowledge Base Article - 306005


1.3 Why do I get "HTTP 500" error (or "(DLL) initialization routine failed") in my browser?


This is because if you have the /3GB boot switch enabled, the ASP.NET worker process (Aspnet_wp.exe) does not start. For more information see Microsoft Knowledge Base Article - 320353
To create and set the "ASPNETENABLE3GB" environment variable as mentioned in the above article, right click MyComputer ->Properties->Advanced > Environment Variables > System variables > New.
Add the variable name in the top text box and the value in the lower textbox.

1.4 I have recently move my Web application from Windows 2k to Windows Server 2003. All works fine in Windows 2K but i am not able to view pages using Windows Server 2003?


You have to enable the ASP.NET in the Web Server Extensions list
From Start -> Settings -> Control Panel -> Administrative Tools -> double click IIS Manager.
Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left.

1.5 What are the Best practices for side-by-side execution of Framework 1.0 and 1.1?


In ASP.NET, applications are said to be running side by side when they are installed on the same computer, but use different versions of the .NET Framework. The following article at www.asp.net details the practices that are recommended ASP.NET Side-by-Side Execution of .NET Framework 1.0 and 1.1


1.6 Can I have VS.NET and the Visual Studio 6.0 installed on the same machine?


Yes! VS.Net works with the .Net framework, while VS6.0 works with MFC or the Windows API directly, for the most part. They can be installed and run on the same machine without any considerations.

1.7 How should I check whether IIS is installed or not?


To verify if IIS is installed, go to your 'Add or Remove Programs' utility in the Control panel and click on the 'Add/Remove Windows Components' in the side menu.
On XP Pro and below, you should see an item called "Internet Information Services (IIS)". If this is checked, IIS should be installed.
On Win2K3, you'll see "Application Server". If this is checked, select it and then click 'Details'. Another form should open which will contain "Internet Information Services (IIS)". If it is checked, IIS should be installed.

1.8 In Visual Studio .NET, how do I create a new ASP.NET application for an existing ASP.NET project?


First create an IIS application using the IIS MMC. Then in Visual Studio .NET, use the "New Project In Existing Folder" project template (at the end of the template list). It will first ask you for the project name (use the same one you created for the IIS application). Click OK button. Then enter in physical folder location.

1.9 Why do I get the error message "Server Application Unavailable The web application you are attempting to access on this web server is currently unavailable. Please hit the "Refresh" button in your web browser to retry your request."?


By default, ASP.NET runs its worker process (Aspnet_wp.exe) with a weak account (the local machine account, which is named ASPNET) to provide a more secure environment. On a domain controller or on a backup domain controller, all user accounts are domain accounts and are not local machine accounts. Therefore, Aspnet_wp.exe fails to start because it cannot find a local account named "localmachinename\ASPNET". To provide a valid user account on the domain controller, you must specify an explicit account in the section of the Machine.config file, or you must use the SYSTEM account. For more details : FIX: ASP.NET Does Not Work with the Default ASPNET Account on a Domain Controller


1.10 In Visual Studio .NET, how do I create a new ASP.NET application which does not have a physical path under wwwroot?


You must first create an IIS application using the IIS MMC. Then in Visual Studio .NET, create a new ASP.NET application and give it the same name you used for the IIS application

1.11 Why do I get the "Unable to find script libruary 'WebUIValidation.js'" error ?


When you install the .Net framework on your web server, it installs some script files (including the above) under the root folder (usually "C:\inetput\wwwroot" if you do a default installation) . You can then find the above file at "C:\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322", for example.
The above problem could happen if you reconfigured your web root directory to be a different one after you installed ASP.Net in your web server. If that is the case, then run 'aspnet_regiis -c' (utility is under %windir%\Microsoft.NET\Framework\v1.1.4322, for example) or copy over manually the above script files into a similar sub-directory below your current web root directory. Also, if you look at the error message in detail, you will notice where the file is supposed to be.

1.12 After installing .NET Framework SP1 the client side validations, or rather validator controls are not working?


The problem seems to be in the javascript file WebValidationUi.js in aspnet_client folder.The changes in that file prevent a page to be submitted. That could be the reason your javascript validations are not working. As a workaround, just copy the old WebValidateionUi.js over the new one.

1.13 How to Configure the ASP.NET Version to use for Each Application(developed using 1.0 or 1.1)?


To configure WebApp1 to use ASP.NET 1.0, follow these steps:
1. Click Start, and then click Run.
2. In the Open text box, type cmd, and then click OK.
3. At the command prompt, locate the following directory: WindowsDirectory\Microsoft.NET\Framework\v1.0.3705\
4. At the command prompt, type one of the following commands:
o To Install ASP.NET 1.0 recursively
aspnet_regiis -s W3SVC/1/ROOT/WebApp1
o To Install ASP.NET 1.0 non-recursively
aspnet_regiis -sn W3SVC/1/ROOT/WebApp1
To configure WebApp2 to use ASP.NET 1.1, follow these steps:
1. Click Start, and then click Run.
2. In the Open text box, type cmd, and then click OK.
3. At the command prompt, locate the following directory: WindowsDirectory\Microsoft.NET\Framework\v1.1.4322\
4. At the command prompt, type one of the following commands:
o To Install ASP.NET 1.1 recursively
aspnet_regiis -s W3SVC/1/ROOT/WebApp2
o To Install ASP.NET 1.1 non-recursively
aspnet_regiis -sn W3SVC/1/ROOT/WebApp2


1.14 How to Configure Different Versions of an ASP.NET Application Running on the Same Web Server?


Here is an exerpt from the KB article: KB 816782
Find the ASP.NET Version Used for the Application View the script map for an ASP.NET application to determine the version of ASP.NET that the application uses. To view the script map for an ASP.NET application, follow these steps:
1. Click Start, point to Programs, and then click Control Panel.
2. Double-click Administrative Tools, and then double-click Internet Information Services (IIS).
3. Expand local computer, expand Web Site, and then expand Default Web Site.
4. Locate the folder that contains the ASP.NET application.
5. Right-click the folder that contains the ASP.NET application, and then click Properties.
6. Click the Directory tab, and then click Configuration. The Application Configuration dialog box opens.
7. Click the Mappings tab, and then select an ASP.NET application extension, such as .asmx or .aspx. The Executable Path column of the dialog box lists the path to the ASP.NET ISAPI version that the application uses. By default, the ASP.NET ISAPI is installed in %WindowsDirectory%\Microsoft.NET\Framework\%versionNumber%. The version number in the path indicates the version number of the ASP.NET ISAPI that the application uses. The ASP.NET ISAPI version determines the version of the runtime that the application uses.

Use Aspnet_regiis.exe to Update the Script Map
To make it easier to reconfigure the script map for an ASP.NET application, each installation of the .NET Framework is associated with a version of the ASP.NET IIS Registration tool (Aspnet_regiis.exe). You can use this tool to remap an ASP.NET application to the ASP.NET ISAPI version associated with the tool.
Note Because Aspnet_regiis.exe is linked to a specific version of the .NET Framework, you must use the appropriate version of Aspnet_regiis.exe to reconfigure the script map for an ASP.NET application. Aspnet_regiis.exe only reconfigures the script map of an ASP.NET application to the ASP.NET ISAPI version associated with the tool

Configure ASP.NET 1.0 for the Application
When ASP.NET 1.1 is configured on the root Web site, follow these steps to configure ASP.NET 1.0 for an application:
1. Click Start, and then click Run. In the Open text box, type cmd, and then click OK.
2. At the command prompt, locate the following directory path:
%WindowsDirectory%\Microsoft.NET\Framework\v1.0.3705\
3. Type the following command to configure the ASP.NET 1.0 application in IIS:

aspnet_regiis -s w3svc/1/root/ApplicationName


To remove ASP.NET 1.0 from this application, repeat steps 1and 2, and then type the following command:

aspnet_regiis -k w3svc/1/root/ApplicationName



Configure ASP.NET 1.1 for the Application When ASP.NET 1.0 is configured on the root Web site, follow these steps to configure ASP.NET 1.1 to run an application:
1. Click Start, and then click Run. In the Open text box, type cmd, and then click OK.
2. At the command prompt, locate the following directory path:
%WindowsDirectory%\Microsoft.NET\Framework\v1.1.4322
3. If ASP.NET 1.1 is not already registered, type the following command to register it: aspnet_regiis -ir Note The -ir option registers ASP.NET 1.1 without updating the scripts in IIS.
4. Type the following to configure the ASP.NET 1.1 application in IIS:

aspnet_regiis -s w3svc/1/root/ApplicationName


To remove ASP.NET 1.1 from this application, repeat steps 1 and 2, and then type the following command:

aspnet_regiis -k w3svc/1/root/ApplicationName




1.15 Why do I get error message "Internet Explorer cannot download MyPage.aspx from MyWebSite.com ..."?


This happens for example, whe you try to export data to excel from a datagrid.
The problem occurs if the server is using Secure Sockets Layer (SSL) and has added one or both of the following HTTP headers to the response message:

Pragma: no-cache
Cache-control: no-cache,max-age=0,must-revalidate


For more details refer PRB: Internet Explorer Is Unable to Open Office Documents from an SSL Web Site


1.16 Why do I get error message "Unable to start debugging on the web server. The server does not support debugging of ASP.NET or ATL Server applications. ..."?


You would get this error if the application mappings for ASP.NET file name extensions (such as .aspx) are not configured correctly in Microsoft Internet Information Services (IIS).
To resolve this go to C:\Windows Directory\Microsoft.Net\Framework\Version and type aspnet_regiis -i to configure the required application mappings correctly
For more information refer PRB: Cannot Debug ASP.NET Web Application














2.1 What is ASP.NET?


ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications.
For more details refer
• What is ASP.NET
• ASP.NET OverView


2.2 Why does my ASP.NET file have multiple tag with runat=server?


This means that ASP.Net is not properly registered with IIS.
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe

use the command: aspnet_regiis.exe -u ---> to uninstall current asp.net version.
use the command: aspnet_regiis.exe -i ---> to install current asp.net version.


For Windows Server 2003, you must use aspnet_regiis -i -enable
This is because of the "Web Service Extensions" feature in IIS 6
(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."

2.3 How to find out what version of ASP.NET I am using on my machine?


VB.NET

Response.Write(System.Environment.Version.ToString() )


C#

Response.Write(System.Environment.Version.ToString() );




2.4 Is it possible to pass a querystring from an .asp page to aspx page?


Yes you can pass querystring from .asp to ASP.NET page .asp

<%response.redirect "webform1.aspx?id=11"%>


.aspx
VB.NET

Response.Write (Request("id").ToString ())


C#

Response.Write (Request["id"].ToString ());




2.5 How to comment out ASP.NET Tags?




<%--Label--%>




2.6 What is a ViewState?


In classic ASP, when a form is submitted the form values are cleared. In some cases the form is submitted with huge information. In such cases if the server comes back with error, one has to re-enter correct information in the form. But submitting clears up all form values. This happens as the site does not maintain any state (ViewState).
In ASP .NET, when the form is submitted the form reappears in the browser with all form values. This is because ASP .NET maintains your ViewState. ViewState is a state management technique built in ASP.NET. Its purpose is to keep the state of controls during subsequent postbacks by the same user. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a control.




If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page If you do not want to maintain Viewstate for any control add the attribute EnableViewState="false" to any control. For more details refer The ASP.NET View State


2.7 Where can I get the details on Migration of existing projects using various technologies to ASP.NET?


Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.
Below are the Code Migration Assistants
• ASP to ASP.NET Migration Assistant
• PHP to ASP.NET Migration Assistant
• JSP to ASP.NET Migration Assistant
Refer Migrating to ASP.Net


2.8 What is the equivalent of date() and time() in ASP.NET?


VB.NET

System.DateTime.Now.ToShortDateString()
System.DateTime.Now.ToShortTimeString()


C#

System.DateTime.Now.ToShortDateString();
System.DateTime.Now.ToShortTimeString();




2.9 How to prevent a button from validating it's form?


Set the CauseValidation property of the button control to False

2.10 How to get the IP address of the host accessing my site?


VB.NET

Response.Write (Request.UserHostAddress.ToString ())


C#

Response.Write (Request.UserHostAddress.ToString ());




2.11 How to access the Parameters passed in via the URL?


Call the Request.QueryStringmethod passing in the key. The method will return the parameter value associated with that key. VB.NET

Request.QueryString("id")


C#

Request.QueryString["id"];




2.12 How to Set Focus to Web Form Controls By Using Client-Side Script?











Enter 1:



Enter 2:








Refer Sample IE Code


2.13 How to display a Wait page while a query is running?


Refer Asynchronous Wait State Pattern in ASP.NET


2.14 How to implement Form based Authentication in ASP.NET application?


For
• VB.NET
• C#


2.15 How to catch the 404 error in my web application and provide more useful information?


In the global.asax Application_error Event write the following code
VB.NET

Dim ex As Exception = Server.GetLastError().GetBaseException()
If TypeOf ex Is System.IO.FileNotFoundException Then
'your code
'Response.Redirect("err404.aspx")
Else
'your code
End If


C#

Exception ex = Server.GetLastError().GetBaseException();
if (ex.GetType() == typeof(System.IO.FileNotFoundException))
{
//your code
Response.Redirect ("err404.aspx");
}
else
{
//your code
}




2.16 Is there a method similar to Response.Redirect that will send variables to the destination page other than using a query string or the post method?


Server.Transfer preserves the current page context, so that in the target page you can extract values and such. However, it can have side effects; because Server.Transfer doesnt' go through the browser, the browser doesn't update its history and if the user clicks Back, they go to the page previous to the source page.
Another way to pass values is to use something like a LinkButton. It posts back to the source page, where you can get the values you need, put them in Session, and then use Response.Redirect to transfer to the target page. (This does bounce off the browser.) In the target page you can read the Session values as required.
Refer to Passing Values Between Web Forms Pages for more information.


2.17 What are the differences between HTML versus Server Control?


Refer
• ASP.NET Server Controls Recommendations
• Introduction to ASP.NET Server Controls


2.18 How can I change the action of a form through code?


You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.
For work around refer to Paul Wilson's Multiple Forms and Non-PostBack Forms - Solution


2.19 Is there any control that allows user to select a time from a clock - in other words is there a clock control?


Peter Blum has developed some controls. Check out Peter's Date Package: TimeOfDayTextBox and DurationTextBox Controls


2.20 How to Compare time?


VB.NET

Dim t1 As String = DateTime.Parse("3:30 PM").ToString("t")
Dim t2 As String = DateTime.Now.ToString("t")
If DateTime.Compare(DateTime.Parse(t1), DateTime.Parse(t2)) < 0 Then
Response.Write(t1.ToString() & " is < than " & t2.ToString())
Else
Response.Write(t1.ToString() & " is > than " & t2.ToString())
End If


C#

string t1 = DateTime.Parse("3:30 PM").ToString("t");
string t2 = DateTime.Now.ToString("t");
if (DateTime.Compare(DateTime.Parse (t1), DateTime.Parse (t2)) < 0 )
{
Response.Write(t1.ToString() + " is < than " + t2.ToString());
}
else
{
Response.Write(t1.ToString() + " is > than " + t2.ToString());
}




2.21 How To work with TimeSpan Class?


VB.NET

Dim adate As DateTime = DateTime.Parse("06/24/2003")
Dim bdate As DateTime = DateTime.Parse("06/28/2003")
Dim ts As New TimeSpan(bdate.Ticks - adate.Ticks)
Response.Write(ts.TotalDays & "
")
Response.Write(ts.TotalHours & ":" & ts.TotalMinutes & ":" & ts.TotalSeconds & ":" & ts.TotalMilliseconds)


C#

DateTime adate = DateTime.Parse("06/24/2003");
DateTime bdate = DateTime.Parse("06/28/2003");
TimeSpan ts = new TimeSpan (bdate.Ticks - adate.Ticks);
Response.Write(ts.TotalDays.ToString () + "
");
Response.Write(ts.TotalHours.ToString() + ":" + ts.TotalMinutes.ToString() + ":" + ts.TotalSeconds.ToString() + ":" + ts.TotalMilliseconds.ToString() );




2.22 Where can I get information on Cookies in ASP.NET?


Refer Mike Pope's article Basics of Cookies in ASP.NET


2.23 Does ASP.Net still recognize the global.asa file?


ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file named global.asax with the same - plus additional - functionality.

2.24 How should I destroy my objects in ASP.Net?


ASP.Net actually has very solid internal garbage collection. So this is not an issue as it was in previous versions of Active Server Pages.
Link to more information: Element


2.25 Are there resources online with tips on ASP to ASP.Net conversions?


Microsoft has deisnged The ASP to ASP.NET Migration Assistant help us convert ASP pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration.
The following Code Migration Assistants are discussed in the link below.
• ASP to ASP.NET Migration Assistant
• PHP to ASP.NET Migration Assistant
• JSP to ASP.NET Migration Assistant
Refer Migrating to ASP.Net
Also refer:
• Microsoft's ASP to ASP.NET Code Migration Assistant
• John Peterson's article Microsoft's ASP to ASP.NET Migration Assistant
• Paolo Cavone's article From ASP to ASP.NET... Painlessly!


2.26 How do I publish my ASP.NET application to my ISP's web server?


Your ISP must first create an IIS application and apply the Front Page Server Extensions to it. Then in Visual Studio .NET, select the "Project | Copy Project" menu. Then enter the URL and select the FrontPage web access method. The "Copy Project" feature copies all of the necessary files to your ISP's machine for your ASP.NET application to run.
You can also FTP your files to your ISP web server. But you must know which files to upload. For more details refer PRB: Remote ASP.NET Projects Require IIS on the Client Computer or FrontPage Server Extensions on the Server Computer


2.27 Why do i get error message "Could not load type" whenever I browse to my ASP.NET web site?


Your code-behind files for either your .aspx or the global.aspx page have not been complied. Use Visual Studio .NET's "Build | Build Solution" menu, or run the command line compiler.
For more details refer PRB: "Could not load type" error message when you browse to .aspx page


2.28 Will the WebMatrix SqlDataSourceControl work with a MySQL connection?


SqlDataSourceControl lets you connect and work with MS SQL DB, while AccessDataSourceControl do the same thing but for MS Access DB. Therefore SqlDataSourceControl can't help you in your MySql connectivity .
For Connectivity with MySql refer Accessing MySQL Database with ASP.NET


2.29 Can I combine classic ASP and ASP.NET pages?


No.
ASP pages can run in the same site as ASP.NET pages, but you can't mix in a page. Also ASP and ASP.NET won't share their session.

2.30 What is the difference between src and Code-Behind?


Src attribute means you deploy the source code files and everything is compiled JIT (just-in-time) as needed. Many people prefer this since they don't have to manually worry about compiling and messing with dlls -- it just works. Of course, the source is now on the server, for anyone with access to the server -- but not just anyone on the web.
CodeBehind attribute doesn't really "do" anything, its just a helper for VS.NET to associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand, and therefore the Src attribute is also gone. Now there is only a dll to deploy, no source, so it is certainly better protected, although its always decompilable even then.

2.31 How can I get the value of input box with type hidden in code-behind?


You can set the runat= server for the hidden control and you can use ControlName.Value to get its value in CodeBehind file

2.32 I have created a .NET user control page (.ascx) but I cannot compile and run it.


User control (ascx) can't be run on it own, but you can drag it onto any web page (aspx) and then run it.

2.33 What is a .resx file?


The .resx resource file format consists of XML entries, which specify objects and strings inside XML tags. This is useful for localization. For more details refer Resources in .resx files


2.34 Is it possible to use a style sheet class directly on a control instead of using inline or page-level formatting ?


Every WebControl derived control has a CssClass property which allows you to set it's format to a style sheet.

2.35 Can I recieve both HTML markup for page and code in the ASP.NET web page's source code portion in the Web browser?


No. The Web browser recieves only HTML markup.
No source code or web control syntax is passed back to the web browser.

2.36 Why can't I put <%@ Page Language="C " %> where at the top of an ASPX file and write my server-side scripts in C ?


The parsers ASP.NET uses to extract code from ASPX files understand C#, Visual Basic.NET, and JScript.NET. You can write server-side scripts in any language supported by a .NET compiler.

2.37 ASP pages that worked pefectly on Windows 2000 Server and IIS 5.0 do not work on Windows 2003 Server with IIS 6.0. ASP.NET pages work fine. Why?


Start -> Settings -> Control Panel -> Administrative Tools -> and double clicking IIS Manager.
Go to the Web Service Extensions tab, click Active Server Pages, then press the "Allow" button on the left

2.38 Why do I get error message "Error creating assembly manifest: Error reading key file 'key.snk' -- The system cannot find the file specified"?


Check the location of the key.snk file relative to the assembly file. Provide an explicit path or a relative path.






2.39 How to get URL without querystring?


VB.NET

Dim stringUri As String = "http://www.syncfusion.com/?id=1&auid=16"
Dim weburi As Uri = New Uri(stringUri)
Dim query As String = weburi.Query
Dim weburl As String = stringUri.Substring(0, stringUri.Length - query.Length)
Response.Write(weburl)


C#

string stringUri = "http://www.syncfusion.com/?id=1&auid=16";
Uri weburi = new Uri(stringUri);
string query = weburi.Query;
string weburl = stringUri.Substring(0, stringUri.Length - query.Length);
Response.Write (weburl);




2.40 What is the best way to output only time and not Date?


Use DateTime as follows VB.NET

Response.Write(DateTime.Now.ToString("hh:mm:ss"))


C#

Response.Write(DateTime.Now.ToString("hh:mm:ss"));




2.41 Do I have to compile code if I am changing the content of my aspx.cs file?


Yes if you have used Codebehind="my.aspx.cs".
Not if you used src="my.aspx.cs" in your page declaration.

2.42 How to grab the referring URL?


VB.NET

Response.Write ( Request.UrlReferrer.ToString())


C#

Response.Write ( Request.UrlReferrer.ToString());




2.43 My ASP code gives an error "Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed" when changed to .aspx?


Use a ") ;




2.58 How to validate that a string is a valid date?


VB.NET

Dim blnValid As Boolean = False
Try
DateTime.Parse(MyString)
blnValid = True
Catch
blnValid = False
End Try


C#

bool blnValid=false;
try
{
DateTime.Parse(MyString);
blnValid=true;
}
catch
{
blnValid=false;
}





2.59 Are namespaces and Class names Case Sensitive?


Namespaces and Class names are case Sensitive. Namespaces imported using the @ Import Directive will cause an error if the correct case is not used.

2.60 How to convert string to a DateTime and compare it with another DateTime?


VB.NET

Dim blntimeIsOk As Boolean = DateTime.Parse("15:00") < DateTime.Parse("08:00")
Response.Write(blntimeIsOk)


C#

bool blntimeIsOk = (DateTime.Parse("15:00") < DateTime.Parse("08:00"));
Response.Write (blntimeIsOk);




2.61 How to get the url of page dynamically?


Use Request.Url property

2.62 How to convert user input in dMy format to Mdy?


VB.NET

Dim dt As DateTime = DateTime.ParseExact("0299", New String() {"My", "M/y"}, Nothing, System.Globalization.DateTimeStyles.None)


C#

DateTime dt = DateTime.ParseExact("0299", new string[] {"My","M/y"}, null,System.Globalization.DateTimeStyles.None);


For more details refer DateTime.ParseExact


2.63 When the User is prompted a File Download dialogbox, if the user selects "Save" then the "Save as" dialog box is displayed. Is there any way for me to retrieve the filename and directory path specified by the user on the File Download dialog box?


Clients do not report information back about where the user selects to save the content, so there isn't an easy way to do this. Instead, you would need to ask the user before using the content-disposition for a file path, and then you could specify the filename parameter for the content-disposition header. Still, the user is free to change that path when actually downloading.

2.64 How to hide or show Controls in server side code?


In any appropriate event write
VB.NET

TextBox1.Visible =not TextBox1.Visible


C#

TextBox1.Visible =!TextBox1.Visible ;




2.65 How to check if the user is using a secure or non secure connection?


The Request Object defines a Property called IsSecureConnection, that will indicate whether http:// or https:// has been used.

2.66 Is it possible to write code in many languages in one ASP.NET project?


You cannot write the code-behind files in different languages in the same project, but you can write the aspx pages and ascx controls in different languages.

2.67 What is the difference between Response.Redirect() and Server.Transfer().


Response.Redirect
• Tranfers the page control to the other page, in other words it sends the request to the other page.
• Causes the client to navigate to the page you are redirecting to. In http terms it sends a 302 response to the client, and the client goes where it's told.
Server.Transfer
• Only transfers the execution to another page and during this you will see the URL of the old page since only execution is transfered to new page and not control.
• Occurs entirely on the server, no action is needed by the client
Sometimes for performance reasons, the server method is more desirable


2.68 How to get the hostname or IP address of the server?


You can use either of these:
• HttpContext.Current.Server.MachineName
• HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]
The first one should return the name of the machine, the second returns the local ip address.
Note that name of the machine could be different than host, since your site could be using host headers


2.69 What is the meaning of validateRequest=true in .net framework1.1?


The value of validateRequest is set to 'true' by default, which means that the framework will automatically deny submission of the '<' and '>' characters.

2.70 What is the different between <%# %> and <%= %>?


The <%# %> is used for databinding where as <%= %> is used to output the result of an expression. The expression inside <%# %> will be executed only when you call the page's or control's DataBind method. The expression inside <%= %> will be executed and displayed as and when it appears in the page.

2.71 What permissions do ASP.NET applications posses by default?


By default ASP.NET Web applications run as ASP.NET user. This user has limited permissions equivalent to the User Group.

2.72 How can I specify the relative path for a file?


Suppose you have following file hierarchy:

default.aspx
Admin/login.aspx
Misc/testpage.aspx



And you are on the login.aspx and want your user to navigate to the default.aspx (or testpage.aspx) file. Then you can use
• Response.Redirect ("../default.aspx")
• Response.Redirect ("../Misc/testpage.aspx")

2.73 How can I specify the "upload a file" input textbox in a form to be read only so that the user can click on the browse button and pick a file but they cannot type anything into the textbox next to the browse button.










2.74 How to change the Page Title dynamically?








C#

//Declare
protected System.Web.UI.HtmlControls.HtmlGenericControl Title1 ;

//In Page_Load
Title1.InnerText ="Page 1" ;




2.75 Why do I get the error message "Object must implement IConvertible". How can I resolve it?


The common cause for this error is specifying a control as a SqlParameter's Value instead of the control's text value.
For example, if you write code as below you'll get the above error:
VB.NET

C#

SqlParameter nameParameter = command.Parameters.Add("@name", SqlDbType.NVarChar, 50);
nameParameter.Value = txtName ;


To resolve it, specify the control's Text property instead of the control itself.
VB.NET




C#

nameParameter.Value =txtName.Text;




2.76 Why is default.aspx page not opened if i specify http://localhost. I am able to view this page if i hardcode it as http://localhost/default.aspx?


If some other default page comes higher in the list, adjust the default.aspx to be the number one entry inside the IIS configuration. If you have multiple websites inside IIS, make sure the configuration is applied on the right website (or on all websites by applying the configuration on the server-level using the properties dialog, configure WWW service).

2.77 Can ASP.NET work on an NT server?


No. For more details refer ASP 1.1 version


2.78 Is it possible to migrate Visual InterDev Design-Time Controls to ASP.NET?


Refer INFO: Migrating Visual InterDev Design-Time Controls to ASP.NET


2.79 How to automatically get the latest version of all the asp.net solution items from Source Safe when opening the solution?


In VS.NET you can go to Tools > Options > Source Control > General and check the checkbox for Get everything when a solution opens.
This retrieves the latest version of all solution items when you open the solution.

2.80 How to convert the datetime into a string for use in the SQL ' statement?




Select a culture:


DateTime in Selected Culture








C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
foreach(CultureInfo cInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
ddlCulture.Items.Add(cInfo.Name);
}
}
}

private void ddlCulture_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Get a CultureInfo object based on culture selection in dropdownlist
CultureInfo cInfo = new CultureInfo(ddlCulture.SelectedItem.Text);
// Get a CultureInfo object based on Invariant culture
CultureInfo cInfoNeutral = new CultureInfo("");
// Display the datetime based on the formatting of the selected culture
TextBox1.Text = Convert.ToString(DateTime.Now , cInfo.DateTimeFormat);
// Create a DateTime variable to hold the Invariant time
DateTime dt ;
dt = Convert.ToDateTime(TextBox1.Text, cInfo.DateTimeFormat);
//Convert the datetime into a string for use in the SQL statement
Label1.Text = "... WHERE ([Date] < '" + Convert.ToString(dt, cInfoNeutral.DateTimeFormat) + "')";
}




2.81 How to make VS.Net use FlowLayout as the default layout rather than the GridLayout?


For VB.NET, go to path C:\Program Files\Microsoft Visual Studio .NET\Vb7\VBWizards\WebForm\Templates\1033
Change the following line in the existing WebForm1.aspx




to




For C#, go to path C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpWebAppWiz\Templates\1033
Change the following line in the existing WebForm1.aspx




to




Note:Before changing any templates it's a good idea to make backup copies of them
Or rather than above approach you can change the behavior for new files on a per project basis in Visual Studio by:
1. Right clicking on the project name (Ex: "WebApplication1)" in Solution Explorer, and select "Properties".
2. From project properties window, under Common Properties>Designer Defaults>Page Layout change "Grid" to "Flow".


2.82 Can I use a DataReader to update/insert/delete a record?


No. DataReader provides a means of reading a forward-only stream of rows from a database.

2.83 What is the difference between Server.Transfer and Server.Execute?


• Server.Transfer is used to End the current weform and begin executing a new webform. This method works only when navigating to a Web Forms page (.aspx)
• Server.Execute is used to begin executing a new webform while still displaying the current web form. The contents of both forms are combined. This method works only when navigating to a webform page(.aspx)


2.84 How to create a login screen in ASP.NET?


Here is a sample login screen:



















User Name



Password







C#

SqlConnection myconnection ;
SqlCommand mycmd ;
string strSql ;
SqlDataReader myReader ;
private void btnLogin_Click(object sender, System.EventArgs e)
{
myconnection=newSqlConnection("Server=localhost;uid=sa;password=;database=northwind;");
strSql = "Select * from usertbl where username=" + "'" + txtUserName.Text + "'" + " and userpassword=" + "'" + txtPassword.Text + "'";
mycmd = new SqlCommand(strSql, myconnection);
myconnection.Open();
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (myReader.Read() )
{
Response.Write("Welcome");
}
else
{
Response.Write("Access Denied");
}
}




2.85 How to format a Telphone number in the xxx-xxx-xxxx format?



C#

double Telno= double.Parse(ds.Tables[0].Rows[0]["TelNo"].ToString());
Response.Write(Telno.ToString("###-###-####"));





2.86 Can two different programming languages be mixed in a single ASPX file?


No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language

2.87 Can I use custom .NET data types in a Web form?


Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. This is also what happens when you add a custom control from the toolbox to your web form.

2.88 How can I have a particular Web page in an ASP.NET application which displays its own error page.


This can be done by setting the ErroPage attribute of Page Directive or ErrorPage property of Page Class to the desired Custom Error Page

<%@Page Language="C#" ErrorPage="specificerropage.htm"%>


In web.config














31.1 What is the Performance comparison between DataSet and DataReader?


Refer Performance Comparison: Data Access Techniques


31.2 How to get the count of records in the Database table using the DataSet?


C#

ds.Tables[0].Rows.Count ;




31.3 How to check if the Dataset has records?



C#

if (ds.Tables[0].Rows.Count == 0 )
{
//No record
}
else
{
//Record Found
}




31.4 How to retrieve value of a field in a dataset?


VB.NET
C#

ds.Tables["TableName"].Rows[0]["ColumnName"];


where TableName and ColumnName could be also integer (not in quotes then) to indicate you refer to the table's or column's index position. Rows(0) indicates the first and only row in DataTable's Rows collection

31.5 How to filter the data in the DataView and display it in some DataControl?


VB.NET



C#

string thefilter = "fieldname=' ' ";
dbDataView.RowFilter = thefilter;
Repeater1.DataSource = dbDataView;
Repeater.DataBind();




31.6 How to truncate the data in the column?




C#

protected string TruncateData( string strNotes )
{
if (strNotes.Length > 20)
{
return strNotes.Substring(0,20) + "...";
}
else
{
return strNotes;
}
}




31.7 How to find the null fields in the datareader?


VB.NET

If dbReader("fieldname").Tostring= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if


C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}




31.8 How to Implement a DataSet SELECT DISTINCT Helper Class?


VB.NET
Sample code 1
C#
Sample Code 2


31.9 I am running the query SQL="Select name from profile where proID=1"; and I am getting the result in Dataset dsdata. Now how do I read the text from the dataset and assign it to textbox1.text ?


VB.NET

dsData.Tables(0).Rows(0)("FieldName").ToString()


C#

dsData.Tables[0].Rows[0]["FieldName"].ToString()




31.10 How to query the database to get all the Table names?




SELECT * FROM information_schema.tables where Table_type='BASE TABLE'




31.11 How to View one record per page in ASP.NET?




runat="server">Product ID
runat="server">Product Name
runat="server" OnDataBinding="txtDataBind">
runat="server">
runat="server" Text="Previous" OnClick ="PrevBtn">
runat="server" Text="Next" OnClick ="NextBtn">


VB.NET




C#

DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Fill the DataSet
if (!Page.IsPostBack )
{
ViewState["CurrentPos"] = 0 ;
this.DataBind() ;
}
}
protected void PrevBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
if (CurrentPos > 0 )
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void NextBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"] ;
CurrentPos += 1 ;
if( CurrentPos > ds.Tables[0].Rows.Count)
{
CurrentPos -= 1 ;
}
ViewState["CurrentPos"] = CurrentPos ;
this.DataBind() ;
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}

protected void txtDataBind(Object sender , System.EventArgs e )
{
try
{
int CurrentPos = (int) ViewState["CurrentPos"];
ViewState["CurrentPos"] = CurrentPos ;
txtProductid.Text = ds.Tables[0].Rows[CurrentPos]["productid"].ToString();
txtProductName.Text = ds.Tables[0].Rows[CurrentPos]["productname"].ToString ();
}
catch (Exception ex)
{
Response.Write(ex.Message) ;
}
}




31.12 How to insert data in database using Textboxes?




runat="server" Text="Add Record">
runat="server">
runat="server">




On Page_Load
VB.NET

if not Page.IsPostBack then
'....
end if


C#

if(!Page.IsPostBack )
{
//...
}


Use namespaces System.Data.SqlClient, System.Data.SqlTypes
On Button Click
VB.NET
On Button Click
C#

string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlCommand cmd =null;
SqlDateTime sqldatenull ;
try
{
sqlStmt = "insert into Employees (FirstName,LastName,HireDate) Values (@FirstName,@LastName,@Date) ";
conString="server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
cmd = new SqlCommand(sqlStmt, cn);
cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 11));
cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 40));
cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
sqldatenull = SqlDateTime.Null;
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@LastName"].Value = txtLastName.Text;
if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Record Inserted Succesfully";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();
}




31.13 When I try to enter a null value for DataTime in Database I get error message "String was not recognized as a valid DateTime" or "Value of type 'System.DBNull' cannot be converted to 'String'"?


Use namespace

System.Data.SqlTypes




C#

if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}




31.14 How to use Parameterized queries in ASP.NET?


The follwoing sample is a good example of parameterized queries: How to insert data in database using Textboxes?


31.15 How to filter distinct records from a normal Select query and display in a web control?


"Select distinct from ".This SELECT statement is used to filter out duplicate results from a query's output. But sometimes the requirement is to use a Stored Procedure which returns the entire data and dsiplay the manipulated distinct data in web server control.
To do this use SortedList
For using SortedList import namespace System.Collections
Stored Procedure

Create Procedure GetSuppliers AS

SELECT * FROM Suppliers
GO






<%#Container.DataItem%>





C#

DataSet ds = new DataSet();
SqlDataAdaptermyda=newSqlDataAdapter("GetSuppliers","server=localhost;database=Northwind;uid=sa;pwd=;");
myda.SelectCommand.CommandType = CommandType.StoredProcedure;
myda.Fill(ds, "Table");
SortedList slist = new SortedList();

foreach( DataRow dr in ds.Tables[0].Rows)
{
if (! slist.ContainsValue(dr["Country"]))
{
slist.Add(dr["Supplierid"].ToString (), dr["Country"].ToString ());
}
}
DataList1.DataSource = slist.GetValueList();
DataList1.DataBind();
//In case of DropDownList
//DropDownList1.DataSource = slist.GetValueList
//DropDownList1.DataBind()




31.16 A field with bit data type value when displayed on a web page shows true/ false how to display a bit value as 1/0?




C#

//Using DataReader
while (dr.Read ())
{
Response.Write (dr["ProductName"] + " ");
Response.Write (Convert.ToInt16 ( dr["discontinued"]) + "
");
}




31.17 When I try to enter null value to DateTime field in database it is saved as 1/1/1900 12:00:00 AM?


To enter Null value in sql server directly you can use Control+0 [Control+Zero]
or
Use SqlDateTime.Null if you want to do it from your application. folowing vb.net shall be helpful .
VB.NET
Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) " < BR > conString="server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)
cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))
cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40))
cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))
sqldatenull = SqlDateTime.Null
cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"
Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try


31.18 How to use Stored Procedures in ASP.NET?


Sub LoginButton_Click(sender As Object, e As EventArgs)
Dim ds As New DataSet
Dim conn As New SqlConnection( _
"Data source=" & DatabaseServer.Text & _
";User id=" & Userid.text & _
";Password=" & Password.Text & _
";Initial catalog=" & Database.Text)
Dim cmd As New SqlCommand("sp_stored_procedures", conn)
Dim adpt As New SqlDataAdapter(cmd)
Try
Status.Text = "" adpt.Fill(ds, "SPs")
SPs.DataSource = ds.Tables("SPs")
SPs.DataTextField = "PROCEDURE_NAME"
SPs.DataBind()
Catch ex as SqlException
Status.Text = ex.Message
EndTry< BR>EndSub

31.19 How to display multiple records using DataTable.Select?


Use namespace System.Data.OleDb VB.NET


C#

OleDbConnection myConnection = new OleDbConnection("Provider= SQLOLEDB.1;DataSource=localhost;database= northwind;UserId=sa;Password=;");
OleDbDataAdapter myda= new OleDbDataAdapter ("Select * from Orders", myConnection);
System.Data.DataSet ds= new DataSet ();
myda.Fill (ds,"table");

DataRow[] dr ;
string id ="ROMEY";// "Field with id ROMEY has more than one records found
string sel ="customerid='"+ id + "'";
dr = ds.Tables [0].Select (sel);
int i;
for(i=0;i
{
Response.Write (dr[i]["Orderid"].ToString() + "\t" +
dr[i]["Customerid"].ToString() + "\t" + dr[i]["Freight"].ToString () +
"
");
}




31.20 How to get the count of items in a dataReader?


VB.NET

DimmycnAsNewSqlConnection("server=localhost;uid=sa;password=;database=northwind;")
Dim mycmd As New SqlCommand("Select * from Products", mycn)
mycn.Open()
Dim dr As SqlDataReader = mycmd.ExecuteReader
Dim i As Integer
While dr.Read
i += 1
End While
Response.Write("Count of Records : " & i)


C#

SqlConnectionmycn=newSqlConnection("server=localhost;uid=sa;password=;database=northwind;");
SqlCommand mycmd = new SqlCommand ("Select * from Products", mycn);
mycn.Open();
SqlDataReader dr = mycmd.ExecuteReader();
int i=0;
while(dr.Read())
{
i+=1;
}
Response.Write("Count of Records : " + i.ToString());





31.21 How to check EOF with SqlDataReader?




C#

SqlConnection myconnection ;
SqlCommand mycmd ;
string strSql ;
SqlDataReader myReader ;

myconnection=newSqlConnection("Server=localhost;uid=sa;password=;database=northwind;");
strSql = "Select count(*) from employees;Select * from employees";
mycmd = new SqlCommand(strSql, myconnection);
myconnection.Open();
int count=(int) mycmd.ExecuteScalar() ;
myReader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (count==0 )
{
Response.Write("No records found");
}
else
{
myReader.NextResult ();
while(myReader.Read ())
{
Response.Write(myReader["Employeeid"].ToString () + "
");
}
}






31.22 How to filter xml data and display data in the DataGrid?

















VB.NET


C#

DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("data1.xml"));
DataView dv = new DataView();
dv = ds.Tables[0].DefaultView;
dv.RowFilter = "prodId='product2-00'";
this.DataGrid1.DataSource = dv;
this.DataBind();




31.23 Why do I get the error message "ExecuteReader requires an open and available Connection. The connection's current state is Closed"?


This error is caused if you have not opened the connection.
Before you read the data using DataReader open the Connection

31.24 Why do I get the error message "The ConnectionString property has not been initialized"?


Check if you have specified the connection string
VB.NET


C#

SqlConnection cn = new SqlConnection("");
OleDbConnection cn = new OleDbConnection("");




31.25 I get the error message "Keyword not supported: 'provider'", when using Sql Server why?


If you are using SqlConnection then the connection string should be as follows:

server=localhost;uid=sa;password=;database=northwind
i.e
server=;uid=;password=;database="


For SqlConnection we do not provide a Provider . Provider is used in cases where OleDbConnection is used.

31.26 Why do I get the error message "ExecuteReader: Connection property has not been initialized"?


This error is caused if there is no Connection object associated with the Command Object. To resolve this
VB.NET

C#

SqlConnection cn = new SqlConnection ("");
'OleDbConnection cn = new OleDbConnection ("");
SqlCommand cmd = new SqlCommand ("Select * from Products", cn);
'OleDbCommand cmd = new OleDbCommand ("Select * from Products", cn);




31.27 Why do I get the error message "There is already an open DataReader associated with this Connection which must be closed first."?


This is caused if you are attempting to use the same DataReader more than once in your code without closing the previous Datareader. Or you might have a DataReader open on the same connection as the DataAdapter/Command uses. So it is not recommended to share a connection between a DataReader and a DataAdapter/Command
• Either close the first connection or,
• if you must keep it open as you are executing another reader from within it, use another connection object.


31.28 I get the error message "Cast from type DBNull to type String is not valid." when I try to display DataReader values on form?


Try VB.NET

txtCountry.Text = dr("FieldName").ToString()


C#

txtCountry.Text = dr["FieldName"].ToString();


or Try
VB.NET

If dbReader("fieldname").ToString= DBnull.Value.ToString()
'Empty field value
Else
'Display value
End if


C#

if (dbReader["fieldname").ToString() == DBNull.Value.ToString() )
{
//Empty field value
}
else
{
//display Value
}




31.29 What is the significance of CommandBehavior.CloseConnection?


To avoid having to explicitly close the connection associated with the command used to create either a SqlDataReader or and OleDbDataReader, pass the CommandBehavior.CloseConnection argument to the ExecuteReader method of the Connection. i.e
VB.NET

dr= cmd.ExecuteReader(CommandBehavior.CloseConnection)


C#

dr= cmd.ExecuteReader(CommandBehavior.CloseConnection);


The associated connection will be closed automatically when the Close method of the Datareader is called. This makes it all the more important to always remember to call Close on your datareaders.

31.30 How to maintain Line feeds when saving data to a database?


Save the data entered in the multiline textbox as
VB.NET

..


C#

...
cmd.Parameters.Add(new SqlParameter("@Notes" ,SqlDbType.NVarChar ));
cmd.Parameters ["@Notes"].Value ="
" + TextBox1.Text + "
";
....
cn.Open();
cmd.ExecuteNonQuery();


To retrieve the Data
VB.NET

Response.Write (ds.Tables(0).Rows(0)("Notes").ToString ())


C#

Response.Write (ds.Tables[0].Rows[0]["Notes"].ToString ());




31.31 How to use the Same DataReader to populate two different ListBoxes?


You cannot use the same DataReader to populate 2 Listboxes.But can try out the below workaround
VB.NET

...


C#

...
cn=newSqlConnection("Server=localhost;uid=sa;database=northwind;pwd=");
cmd= new SqlCommand ("select * from products;select * from products", cn);
cn.Open();
dr = cmd.ExecuteReader();
ListBox1.DataSource = dr;
ListBox1.DataTextField = "productname";
ListBox1.DataBind();
dr.NextResult();
ListBox2.DataSource = dr;
ListBox2.DataTextField = "productname";
ListBox2.DataBind();




31.32 How to resolve the error message "Cannot implicitly convert type 'string' to 'System.DateTime' " when using a DataReader?



DateTime dt= ((DateTime) dr["hiredate"]).ToString();




31.33 Why do I get the error message "Value cannot be null. Parameter name: dataSet "?


The cause of this error may be that you have declared a dataset but have not written the following statement
VB.NET

ds= new DataSet()


C#

ds= new DataSet();




31.34 Why do I get the error message "The SelectCommand property has not been initialized before calling 'Fill'. "?


You have to supply the Sql Statement or Stored Procedure for the DataAdapter as
VB.NET

da.SelectCommand.CommandText = "Select * from "


or

da = new SqlDataAdapter ("Select * from ", cn)


C#

da.SelectCommand.CommandText ="Select * from ";


or

da = new SqlDataAdapter ("Select * from ", cn);




31.35 How to use OleDb DataSet?


Use namespace System.Data.OleDb



C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";
string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(strsql, cn);
da.Fill(ds, "T1");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();





31.36 How to use OleDb DataReader?



C#

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("nwind.mdb") + ";";
string strsql = "Select * from Customers";
OleDbConnection cn = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand (strsql, cn);
cn.Open ();
OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = dr;
DataGrid1.DataBind();




31.37 How to loop through a Dataset to display all records?



C#

//Fill the DataSet
foreach (DataRow dr in ds.Tables[0].Rows)
{
foreach( DataColumn dc in ds.Tables[0].Columns)
{
Response.Write(dr[dc.ColumnName].ToString());
}
}























9.1 What is the difference between authentication and authorization?


Authentication is the process of identifying and verifying who the client accessing the server is.
For example, if you use
• Windows authentication and are browsing an ASP.NET page from server -- ASP.NET/IIS would automatically use NTLM to authenticate you as SYNCFUSION\user1 (for example).
• Forms based authentication, then you would use an html based forms page to enter username/password -- which would then check a database and authenticate you against the username/password in the database.

Authorization is the process of determining whether an authenticated user has access to run a particular page within an ASP.NET web application. Specifically, as an application author decide to grant or deny the authenticated user "SYNCFUSION\user1" access to the admin.aspx page. This could be done either by explictly granting/denying rights based on the username -- or use role based mappings to map authenticated users into roles (for example: an administrator might map "SYNCFUSION\user1" into the "Power Users" role) and then grant/deny access based on role names (allowing a degree of abstraction to separate out your authorization policy).


9.2 How to implement authentication via web.config?


Include the element.








9.3 How to run a Web application using the permission of an authenticated user?


Use the element in the web.config






9.4 Which are the different ASP.NET authentication modes?


ASP.NET supports the following Authentication Providers
• Windows : Is used in conjunction with IIS authentication. Authentication is performed by IIS in one of three ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access
• Forms : The user provides credentials and submits the form.
• Passport : Centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites.
• None : No Authentication provided. This is default Authentication mode

In the web.config file, you can specify this setting:


mode= " [ Windows | Forms | Passport | None ] ">






9.5 How to determine the Windows User from a Web form Application?


Use the System.Security.Principal namespace.
VB.NET


C#

WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
Response.Write(wp.Identity.Name);





























Datagrid

25.1 Why do I get the Columns twice in the datagrid. I am using BoundColumns and TemplateColumns in DataGrid?


Set the AutogenerateColumns= False. By Default it is set to true for a datagrid

25.2 How to Format and display currency with n decimal points in a BoundColumn.


Set the Dataformatstring of the boundcolumn to {0:Nn} where n=> number of decimal points For more details refer Format Function


25.3 How do I specify more than one parameter for my HyperlinkColumn?

















25.4 Why am I getting an 'AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection' Error?


You are probably trying to implement paging in a DataGrid while binding the DataGrid with a DataReader. To fix this, instead of using a DataReader use a DataSet

25.5 How do I use a "helper function" to change the column value as Boolean in database to be displayed as Yes/No in Datagrid?








<%#ShowStatus(bool.Parse(DataBinder.Eval(Container.DataItem,"Discontinued").ToString()))%>







C#

protected string ShowStatus(bool someval)
{
if (someval == true)
{
return "Yes";
}
else
{
return "No";
}
}




25.6 How to display only date part in the Datagrid if the Date is of DateTime datatype in the database?


Set the DateFormatString as {0:d}

25.7 How to open a new window with multiple parameters when clicked on a hyperlink in a column in a datagrid?


The column should be defined as a TemplateColumn as follows and the NavigateUrl for that hyperlink can be set as follows to open a new window with parameters varying based on the row in which the hyperlink is present.



NavigateUrl= <%#"javascript:my_window=window.open('webform2.aspx?id=" + DataBinder.Eval(Container.DataItem,"productid").ToString() + "&Supplierid= "+DataBinder.Eval(Container.DataItem,"SupplierID").ToString()+"','my_window','width=300,height=300');my_window.focus()" %>
text=<%#DataBinder.Eval(Container.DataItem,"ProductName").ToString() %>>





The above approach would avoid the problem of showing the screen of [Object] on the parent page

25.8 How to display hierarchical data in a DataGrid?


Check out Denis Bauer's custom control HierarGrid


25.9 How do I conditionally set the text color of a cell in my Datagrid based on the cell's/fields's value?


In the ItemDataBound event you can access the Cells() collection of the current Datagrid item (or row) and set it's ForeColor.





C#

protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if((e.Item.ItemType ==ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) )
{
if (Convert.ToInt16 (e.Item.Cells[6].Text) >15 )
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Green;
}
else
{
e.Item.Cells[6].ForeColor = System.Drawing.Color.Red;
}
}
}


In Cells[x]/Cells(x) x=> index number to the list of fields in the row.

25.10 When I open my new window using Javascript, all elements appear great, but the original window just displays [Object] why?


Check out How to open a new window with multiple parameters using datagrid?


25.11 How to populate a DataGrid using a DataReader?







Use Namespace System.Data.SqlClient
VB.NET

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Try
cn=NewSqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
cmd = New SqlCommand("select * from employees ", cn)
cn.Open()
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = rdr
DataGrid1.DataBind()
Catch ex As Exception
Response.Write(ex.Message.ToString())
Finally
rdr.Close()
cn.Close()
End Try
End Sub 'Page_Load


C#

SqlConnection cn ;
SqlCommand cmd ;
SqlDataReader rdr ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
try
{
cn=newSqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
cmd = new SqlCommand( "select * from employees ", cn);
cn.Open();
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection );
DataGrid1.DataSource = rdr;
DataGrid1.DataBind();
}
catch (Exception ex)
{
Response.Write (ex.Message.ToString ());
}
finally
{
rdr.Close();
cn.Close();
}
}




25.12 How to populate a DataGrid using a DataSet?







Use the namespace System.Data.SqlClient
VB.NET

Dim cn As SqlConnection
Dim da As SqlDataAdapter
Dim ds As DataSet
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn=NewSqlConnection("Server=localhost;uid=sa;pwd=;database=northwind")
da = New SqlDataAdapter("Select * from products", cn)
ds = New DataSet
da.Fill(ds, "Products")
DataGrid1.DataSource = ds.Tables(0)
'DataGrid1.DataSource = ds
'DataGrid1.DataSource = ds.Tables("Product")
DataGrid1.DataBind()
End Sub


C#

SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
cn=newSqlConnection("Server=localhost;uid=sa;pwd=;database=northwind");
da= new SqlDataAdapter ("SELECT * FROM Products ", cn);
ds= new DataSet ();
da.Fill (ds, "Product");
DataGrid1.DataSource =ds.Tables[0];
//DataGrid1.DataSource= ds;
//DataGrid1.DataSource= ds.Tables["Products"];
DataGrid1.DataBind ();
}




25.13 Why do I get "Could not lock file" and "cannot open file" exceptions when bound to a mdb file?


You could get this error for the following reasons:
1. When you create a project afresh, add a new OleDbDataAdapter to the form and link to the mdb file, the connection object created in the process will keep an open connection to the mdb file which is what will cause the above "Could not lock file" exception during runtime. To workaround this, go to "Server Explorer" in your IDE, right click on the corresponding "Connection entry" and select Close Connection. This should fix the problem.
2. The "cannot open file" exception could then occur if you have not provided enough permissions on the mdb file to allow the .net runtime to lock it. To ensure enough permissions, open it's properties, select the Security tab and add a "Everyone" account granting "Full Control" to it. This should let the .net runtime lock the file.


25.14 I am binding the DataGrid to a datasource at runtime. After binding I want to populate a listbox with the column headers from the datagrid. How can I reference the column headertext for each column in the datagrid and then add them to my listbox?


In the ItemDataBound Event write following code VB.NET

C#

if (e.Item.ItemType== ListItemType.Header)
{
for(int i = 0; i <= e.Item.Cells.Count-1 ; i++)
{
this.ListBox1.Items.Add(new ListItem(e.Item.Cells[i].Text));
}
}




25.15 When I try to do an Update from my Datagrid, I keep getting the old/original values. Why?


This could happen if you are calling .DataBind everytime the Page is loaded
To avoid this call Databind only for the first request and not for subsequent postbacks.
VB.NET

C#

if (!Page.IsPostBack)
{
'Your databinding code
}




25.16 How can I sort a BoundColumn?


Set the SortExpression to the Field Name

25.17 How can I hide the HeaderText of the DataGrid?


Set the ShowHeader property of the DataGrid to false

25.18 How to add a mailto link inside a datagrid?






">
<%# DataBinder.Eval(Container.DataItem,"email").ToString() %>








25.19 How to do Simple sorting using DataGrid?







C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(! Page.IsPostBack )
{
BindDataGrid("ProductId");
}
}

protected void SortData(Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e )
{
BindDataGrid(e.SortExpression.ToString());
}

void BindDataGrid(string sortfield)
{
//Fill the Dataset
//.....
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = sortfield;
DataGrid1.DataSource = dv;
DataGrid1.DataBind();
}




25.20 How to do Paging using DataGrid?







VB.NET


C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(! Page.IsPostBack )
{
Binddata();
}
}

protected void PageData(Object source , System.Web.UI.WebControls.DataGridPageChangedEventArgs e )
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Binddata();
}

void Binddata()
{
//Populate the DataGrid using DataSet
}
25.31 How to set a Datagrid Column to invisible when that Column is an AutoGeneratedColumn?


In the DataGrid's declaration, add the following code in OnItemDataBound event
VB.NET


C#

DataView dv = DataGrid1.DataSource ;//Bind you DataGrid1 in Page_Load to DataView
DataColumnCollection dc = dv.Table.Columns;
e.Item.Cells[dc.IndexOf(dc["field_name"])].Visible = false;




25.32 How to use the DataFormatString to format DataGrid data dynamically?


In the ItemDataBound Event of DataGrid write following code.
VB.NET


C#

DataSet ds = (DataSet)DataGrid1.DataSource ;
DataView dv = ds.Tables[0].DefaultView ;
DataColumnCollection dcCol = dv.Table.Columns ;
if ((e.Item.ItemType == ListItemType.Item )||( e.Item.ItemType == ListItemType.AlternatingItem ))
{
e.Item.Cells[dcCol.IndexOf (dcCol ["UnitPrice"])].Text = DataBinder.Eval(e.Item.DataItem, "UnitPrice", "{0:c}");
}




25.33 How to set the maxlength of a textbox (in the EditTemplate of DataGrid) based on a field value in the record?










25.34 How to add an attribute to the Table generated by the DataGrid?


VB.NET

'Bind DataGrid
DataGrid1.Attributes.Add ("Description", "This table displays Product Description" )


C#

//Bind DataGrid
DataGrid1.Attributes.Add ("Description", "This table displays Product Description" );


Note : By doing a ViewSource you can find the Attribute Description for the Table that displays the DataGrid data

25.35 Why do I get the error message " CS1502: The best overloaded method match for 'xxx(string)' has some invalid arguments " when I use Helper function in DataGrid?


The function xxx() is expecting a string, but DataBinder.Eval() returns an object. So you must cast the result of DataBinder.Eval() to a string (or, in this case, just use .ToString()).
i.e, in your template do:

<%#xxx(DataBinder.Eval(Container.DataItem, "field_name").ToString()) %>


VB.NET


C#

<%# xxx((string) DataBinder.Eval(Container.DataItem, "field_name"))%>


Either of these should work.

25.36 How to confirm delete in DataGrid using LinkButton?



















C#

string sqlStmt ;
string conString ;
SqlConnection cn =null;
SqlDataAdapter da =null;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
conString="server=localhost;database=Northwind;uid=sa;pwd=;";
cn = new SqlConnection(conString);
if (!Page.IsPostBack )
{
BindData();
}
}
void BindData()
{
sqlStmt = "select * from emp ";
ds= new DataSet ();
da = new SqlDataAdapter (sqlStmt, cn);
da.Fill (ds,"t1");
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

protected void ItemDB(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
switch(e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
{
LinkButton btn = (LinkButton)e.Item.FindControl("btnDelete");
btn.Attributes.Add("onclick", "return confirmmsg();");
break;
}
}
}

protected void ItemCmd(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
this.DeleteRow(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
}
BindData();
}

private void DeleteRow(string empid)
{
SqlCommand cmd = new SqlCommand("DELETE FROM Emp WHERE employeeid ="+ empid ,cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}






25.37 How to hide and show a Column based on the authenticated user?


In the DataGrid_ItemDataBound Event write the following code
VB.NET



C#

if ( ! User.Identity.IsAuthenticated )
{
e.Item.Cells[1].Visible =false;
}




25.38 How to use a dropdownlist in a DataGrid?


Step 1: Display the Data in the Datagrid Initially the Datagrid is populated with the records in the db The field Discontinued is of data type bit in the db i.e 0/1.
To display it as yes/no in the Datagrid a helper function ShowVal(...) is called
Step 2: To Edit the Datagrid ,
When the edit button is clicked it should display field Discontinued as Yes/No
• To update the record the user should get a choice to Select Yes/No using dropdownlist
• By default the dropdownlist should be set to the value in the database
o So the DataSource property of the dropdownlist is set to BindTheDiscontinued()
o and OnPreRender property does the task of setting the value from the db to the dropdownlist

OnEditCommand="DataGrid1_Edit" OnCancelCommand="DataGrid1_Cancel" runat="server">



















C#

string strDiscontinued;
GetData obj;
string strSql;
string strConn;
DataSet ds;
SqlDataReader dr;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn="server=localhost;uid=sa;pwd=;database=northwind";
if (!Page.IsPostBack )
{
BindGrid();
}
}


//To Bind the DataGrid
void BindGrid()
{
obj=new GetData ();
strSql = "Select productid, discontinued from Products";
ds=obj.GetDataFromTable (strSql ,strConn);
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}

//To display Yes/No for True/False
protected string ShowVal(bool blnval)
{
if (blnval==true)
{
return "Yes";
}
else
{
return "No";
}
}

//Bind the Data to the dropdownlist in the EditTemplate
protected SqlDataReader BindTheDiscontinued()
{
obj=new GetData ();
strSql ="SELECT distinct 'Discontinued' =" ;
strSql+=" CASE ";
strSql+=" WHEN Discontinued = 1 Then 'Yes'" ;
strSql+=" ELSE 'No'" ;
strSql+=" END " ;
strSql+=" From Products ";
dr=obj.GetSingleDataUsingReader (strSql ,strConn);
return dr;
}


//Set the Text of the Dropdownlist to the field value in Database

protected void SetDropDownIndex(Object sender ,System.EventArgs e )
{
DropDownList ed ;
ed = (DropDownList) sender;
ed.SelectedIndex = ed.Items.IndexOf(ed.Items.FindByText(strDiscontinued));
}


//For Edit Update Cancel
public void DataGrid1_Edit(Object sender, DataGridCommandEventArgs e)
{
strDiscontinued = ((Label )e.Item.FindControl("lblDiscontinued")).Text;
DataGrid1.EditItemIndex = (int)e.Item.ItemIndex;
BindGrid();
}

public void DataGrid1_Update(Object sender, DataGridCommandEventArgs e)
{
DropDownList TempList ;
String TempValue ;
TempList = (DropDownList) e.Item.FindControl("ddlDiscontinued");
TempValue = TempList.SelectedItem.Value;
//Place update code here
Response.Write (TempValue);
DataGrid1.EditItemIndex = -1;
BindGrid();
}
public void DataGrid1_Cancel(Object sender, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
BindGrid();
}



//Functions used in Class GetData.cs

SqlConnection mycn;
SqlDataAdapter myda;
SqlCommand mycmd;
DataSet ds;
String strConn;
SqlDataReader myReader;
public DataSet GetDataFromTable(string strSQL ,string strConnString)
{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter (strSQL, mycn);
ds= new DataSet ();
myda.Fill (ds,"Table");
return ds;
}
catch(Exception ex)
{
throw new Exception (ex.Message.ToString ());
}
finally
{
mycn.Close ();
}
}

public SqlDataReader GetSingleDataUsingReader(string strSQL ,string strConnString)
{
try
{
strConn=strConnString;
mycn = new SqlConnection(strConn);
mycmd = new SqlCommand (strSQL, mycn);
mycn.Open ();
myReader=mycmd.ExecuteReader(CommandBehavior.CloseConnection );
return myReader;
}
catch(Exception ex)
{
throw new Exception (ex.Message.ToString ());
}
finally
{
//mycn.Close ();
}
}




25.39 How to set a different color for every alternate row of a datagrid?


Use the Tag

25.40 How to add a counter column to a DataGrid?








<%#getCount%>






Code behind
VB.NET

C#

int count =0;
protected int getCount()
{
count = count + 1;
return count;
}

private void Page_Load(object sender, System.EventArgs e)
{
//Populate the Datagrid populating data from the database
//....
}


25.41 How to change the HeaderText of the Datagrid?


Method 1 : Set the HeaderText Property of the BoundColumn/TemplateColumn









<#%DataBinder.Eval(Container.DataItem, "LastName").ToString()%>






Method 2 : Dynamically change the HeaderText in the ItemDataBound Event of the DataGrid





C#

private void Page_Load(object sender, System.EventArgs e)
{
//Populate the DataGrid
}

protected void ItemDB(Object sender ,System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if (e.Item.ItemType == ListItemType.Header)
{
e.Item.Cells[0].Text = "Employee ID";
e.Item.Cells[1].Text = "First Name";
e.Item.Cells[2].Text = "Last Name";
}
}




25.42 How to select a record in the datagrid and start editing/updating the record using textboxes?




style="Z-INDEX: 101; LEFT: 15px; POSITION: absolute; TOP: 23px"
runat="server" >





runat="server">
runat="server">
runat="server" Text="Update">
runat="server">





C#

SqlConnection cn;
SqlDataAdapter da ;
SqlCommand cmd ;
string strsql ;
DataSet ds ;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn=newSqlConnection("Server=localhost;uid=sa;pwd=;database=northwind;");
if(!Page.IsPostBack)
{
//Code to Bind the data to the Datagrid
BindData();
}
}

void BindData()
{
DataGrid1.DataSource = GetData("Select * from Region");
DataGrid1.DataBind();
}
DataSet GetData(string strSql)
{
da = new SqlDataAdapter(strSql, cn);
ds = new DataSet();
da.Fill(ds);
return ds;
}

protected void ItemCommand(Object source,System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
//'Fill the Textboxes with relevant data
FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text);
lblMessage.Text="";
}
}

void FillTheData(string RegionID,string RegionDescription)
{
txtRegionID.Text = RegionID;
txtRegionDescription.Text = RegionDescription;
}

private void btnUpdate_Click(object sender, System.EventArgs e)
{
try
{
strsql = "Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId";
cmd = new SqlCommand(strsql, cn);
cmd.Parameters.Add(new SqlParameter("@RegionId", SqlDbType.Int));
cmd.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NVarChar, 40));
cmd.Parameters["@RegionId"].Value = Convert.ToInt32(txtRegionID.Text);
cmd.Parameters["@RegionDescription"].Value = txtRegionDescription.Text;
cn.Open();
cmd.ExecuteNonQuery();
BindData();
lblMessage.Text = "Updated Successfully";
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
}
finally
{
cn.Close();
}
}






25.43 How can I show what page the user is on using in-built paging functionality. CurrentPageIndex Property Shows Up as 0?


In PageIndexChanged event write
VB.NET

C#

int pageindex = DataGrid1.CurrentPageIndex + 1 ;
LblPageInfo.Text = "Page " + pageindex.ToString() + " of " + DataGrid1.PageCount.ToString() ;




25.44 How to display "No data" when a field value is null?








C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack )
{
//Populate the DataGrid
}
}

protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
{
if( e.Item.Cells[1].Text == " ")
{
e.Item.Cells[1].Text = "No data";
}
}
}


In Cells[x]/Cells(x) x=> index number

25.45 How to change the value of a field before it gets displayed in the datagrid?








C#

protected void ItemDB (Object s , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if ((e.Item.ItemType ==ListItemType.Item) ||(e.Item.ItemType ==ListItemType.AlternatingItem))
{
switch ( e.Item.Cells[3].Text.Trim() )
{
case "Sales Representative":
e.Item.Cells[3].Text = "SR";
break;
case "Vice President, Sales":
e.Item.Cells[3].Text = "VP";
break;
case "Sales Manager":
e.Item.Cells[3].Text = "SM";
break;
case "Inside Sales Coordinator":
e.Item.Cells[3].Text = "ISC";
break;
default :
e.Item.Cells[3].Text = e.Item.Cells[3].Text;
break;
}
}
}




25.46 How to use a ButtonColumn in a DataGrid?








Text="Click">






C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
//Populate the DataGrid
}
}

protected void ItemCmd(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e )
{
if (e.CommandName.ToString () == "Show")
{
Response.Write(e.Item.Cells[1].Text);
}
}





25.47 How to display a Master Detail data using DataGrid?








<%#DataBinder.Eval(Container.DataItem,"OrderId")%>








C#

SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
cn=newSqlConnection("Server=localhost;uid=sa;pwd=;database=northwind");
if (!Page.IsPostBack)
{
da= new SqlDataAdapter ("SELECT orderid FROM orders ", cn);
ds= new DataSet ();
da.Fill (ds, "Orders");
DataGrid1.DataSource = ds;
DataGrid1.DataBind ();
}
}

protected void ItemDB(Object sender,DataGridItemEventArgs e )
{
if ((e.Item.ItemType == ListItemType.Item)||(e.Item.ItemType == ListItemType.AlternatingItem ))
{
DataGrid dgDetails = new DataGrid();
int orderid =(int) ((DataRowView)e.Item.DataItem)["OrderID"] ;
dgDetails.DataSource = GetOrderDetails(orderid );
dgDetails.DataBind();
e.Item.Cells[1].Controls.Add(dgDetails);
}
}

DataSet GetOrderDetails(int id )
{
da= new SqlDataAdapter ("SELECT * FROM [Order Details] where orderid= " + id, cn);
ds= new DataSet ();
da.Fill (ds, "OrderDetails");
return ds;
}




25.48 I have set the ItemStyle and the AlternatingItemStyle tags for DataGrid control but they aren't working correctly , why?


DataGrid generates an HTML Table, with TableRows and Cells. If you already have some display properties set for
... make sure to check them in the Stylesheet. Whatever properties you set there will normally override whatever you add into your DataGrid's Item styles.

25.49 How to display the checkbox checked or unchecked for a bit data type value in the DataBase?








>








25.50 How to do alphabetical paging in ASP.NET?


• Step 1: Create linkbuttons to display the alphabets at the footer of the datagrid
• Step 2: Add this buttons in the ItemCreated event . Use the CommandName and CommandArgument properties of the LinkButton to identify them
• Step 3: To handle the Paging , In the ItemCommand Event respond to action based on the CommandName and CommandArgument of LinkButton that caused event to be raised.






C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!Page.IsPostBack )
{
BindGrid("");
}
}

void BindGrid(string stralpha)
{
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
cn=newSqlConnection("Server=localhost;uid=sa;pwd=;database=pubs");
string strsql ="Select * from authors ";
if (stralpha=="")
{
strsql = strsql ;
}
else
{
strsql = strsql + " where au_lname like'" + stralpha + "%'";
}
da= new SqlDataAdapter (strsql,cn);
ds= new DataSet ();
da.Fill (ds, "Product");
if (ds.Tables [0].Rows.Count ==0)
{
Response.Write ("No Data Found");
DataGrid1.DataSource=null;
DataGrid1.DataBind ();
}
else
{
DataGrid1.DataSource =ds;
DataGrid1.DataBind ();
}
}

protected void ItemCreated(Object sender , System.Web.UI.WebControls.DataGridItemEventArgs e )
{
if (e.Item.ItemType == ListItemType.Footer)
{
e.Item.Cells.Clear();
TableCell tc = new TableCell();
tc.ColumnSpan = 2;
e.Item.Cells.Add(tc);
LiteralControl lc;
LinkButton lb;
string s="" ;
for (char c='A' ; c<= 'Z' ; )
{
lc = newLiteralControl ();
lb = new LinkButton ();
s = c.ToString() ;
lc.Text =" ";
lb.CommandName ="alpha";
lb.CommandArgument= s;
lb.Text=s;
c =(char)((int)c +1) ;
tc.Controls.Add(lb);
tc.Controls.Add(lc);
}
}
}
protected void ItemCommand(Object source , System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "alpha" )
{
BindGrid(e.CommandArgument.ToString ());
}
}


25.81 How should I avoid getting blank page on click of linkbutton inspite of setting the EnableViewState= true for DataGrid?


You should bind the data each time the page is loaded

25.82 Why do I get a blank page when I click the linkbutton in the Datagrid, I am also handling PostBack on the page? The ItemCommand Event does not seem to trigger?


You must have set the EnableViewState property of DataGrid to false

25.83 How to export data in Datagrid on a webform to Microsoft Excel?


Two techniques for exporting the data in the DataGrid:
• Using the Excel MIME Type (or Content Type)
With server-side code, you can bind the DataGrid to your data and have the data open in Excel on a client computer. To do this, set the ContentType to application/vnd.ms-excel. After the client receives the new stream, the data appears in Excel as if the content was opened as a new page in the Web browser.
• Using Excel Automation
With client-side code, you can extract the HTML from the DataGrid and then Automate Excel to display the HTML in a new workbook. With Excel Automation, the data always appears outside the browser in an Excel application window. One advantage to Automation is that you can programmatically control Excel if you want to modify the workbook after the data is exported. However, because Excel is not marked as safe for scripting, your clients must apply security settings in the Web browser that allow Automation.

For more details refer How To Export Data in a DataGrid on an ASP . NET WebForm to Microsoft Excel


25.84 How to export DataGrid data to excel?


Use namespace System.IO
VB.NET

C#

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
//Bind the DataGrid to DataSet
DataGridToExcel (DataGrid1, Response);
}
protected void DataGridToExcel(DataGrid dGridExport , HttpResponse httpResp)
{
httpResp.Clear();
httpResp.Charset = "";
httpResp.ContentType = "application/vnd.ms-excel";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
DataGrid dGrid = new DataGrid();
dGrid = dGridExport;
dGrid.HeaderStyle.Font.Bold = true;
dGrid.DataBind();
dGrid.RenderControl(htmlWrite);
httpResp.Write(stringWrite.ToString());
httpResp.End();
}

 
,