#.NET Interview Questions and Realtime Discussions ,C# Realtime Interview Questions,C# Questions for MNCs like Cap Gemini,CTS,HP,Patni,Sasken
What is the top .NET class that everything is derived from?
System.Objects
What is an abstract class?
The abstract modifier can be used with classes, methods, properties, indexers, and events.
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.
Abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
An abstract method is implicitly a virtual method.
Abstract method declarations are only permitted in abstract classes.
Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example:
public abstract void MyMethod();
________________________________________
abstract class is a prototype of a class. it is used to provide partial
class implementation. abstract class contain abstract method which can be implemented by derived class.
some rules for abstract class are following-:
1) an object of an abstract class can never be created.
2)you can not declare an abstract method outside the abstract class.
3)can not be declared sealed.
WHAT IS THE ADVANTAGE OF SERIALIZATION?
Serialization is the process of maintaing object in the form stream. it is useful in case of remoting.
Serialization is the process of converting object into byte stream which is useful to transport object(i.e remoting),persisting object(i.e files,database)
SERIALIZATION IS PROCESS OF LOADING THE OBJECT STATE IN THE FORM OF BYTE STREAMS IN DATABASE/FILE SYATEM.
Can we inherit the java class in C# class,how?
Java Programming language is not supported with .Net Framework hence you cannot inherit javaclass in C# class.Also Java has JavaByte code after compiling similar to MSIL which is similar but cannot inherit due to framework support.
Are C# destructors the same as C++ destructors?
No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.
What is wrapper class? is it available in c#?
Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it . For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable .
wrapper class are those class in which we can not define and call all predefined function .it is possible in java not C#.
Which tool is used to browse the classes, structs, interfaces etc. in the BCL?
wincv as in Windows Class View
How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released.
What happens when a C# project has more than 1 Main methods
f the project is compiled using /main switch with the compiler then the project compiles successfully.
For example:
class A
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class A");
}
}
class B
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class B");
}
}
Now compile with the /main switch with the C# compiler like
csc MultipleMain.cs /main:A
This will compile without error and while executing it will show Main in class A
Attempting to compile an application consisting of multiple classes with defined Main methods and not specifying the /main switch will result in a compiler error.
How do you refer parent classes in C#? A) Super B) This C) Base
This keyword is used for reffering current object and Base keyword is used for referring parrent class. so ans. is C.
Super: Super is used to Refer the Base Class in JAVA
This: This is used to Refer the Current or Child Class in C#
Base: Base is used to Refer The Parent or Base Class
What is object pooling
Defination: A performance optimization based on using collections of pre-allocated resources, such as objects or database connections
With the advent of the .NET platform, writing code that pools objects and threads has become a simple task. By using the Threading and Collections namespaces, you can create robust object pooling applications. This could also be done by implementing COM+ interop interfaces into your code.
Which method is actually called ultimately when Console.WriteLine( ) is invoked?
A) Append( )
B) AppendFormat( )
C) Tostring( )
Ans: B, AppendFormat() method is called.
What is an Assembly?
An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. The entire process will run in the background of your application; there is no need for you to learn deeply about assemblies. However, a basic knowledge about this topic will help you to understand the architecture behind a .NET application.
An assembly is used by the .NET CLR (Common Language Runtime) as the smallest unit for: deployment; version control; security; type grouping and code reuse. Assemblies consists of a manifest and one or more modules and/or files like HTML, XML, images, video clips,...
An assembly can be thought of as a logical DLL and must contain a single manifest and may optionally contain type meta data, MSIL (Microsoft Intermediate Language) and resources.
Assemblies come in 2 flavors: application private and shared. Application private assemblies are used by one application only. This is the default style of assembly. Such assemblies must reside in the application folder.
Shared assemblies are meant to be used by more than one application. They must have a
globally unique name and must be defined in the GAC (Global Assembly Cache). To learn more about viewing the GAC
Basically there are two kind of assemblies when it comes to deployment.
Private Assemblies
Shared Assemblies
Private assemblies are the ones which are in your application folder itself. They can be easily and uniquely identified by their name.
These type of assemblies can be deployed simply by copying them to the bin folder of your application.
Shared Assemblies are those which can be shared by multiple applications on the machine.
For this we have to place the Shared assembly in the GAC.
Now since we can install any application or assembly created by any company, that is we install assemblies from oracle, microsoft and similarly from many other companies.
There is always a possiblity that they may use the same assembly name as your assembly name.
If such type of assemblies are placed in the GAC then we cannot uniquely identify a particular assembly.But if we give a strong name to the assmebly then it is like a unique identifier for the assembly.It is Globally unique.
Strong name consists of
1. Name of the assembly
2. Public key token
3. optionally any resources
4. Version Number
So basically to uniquely identify a particular assembly from the GAC we have to give it a strong name. Its that simple.
The Shared assembly can be deployed in to GAC by using the GACUTIL tool with the -i switch
gacutil -i assemblyname
or simply copying it to the assembly folder in the windows directory (XP) or WINNT directory(others)
Also there are Satellite Assemblies which contian only resources like strings, images etc.
Also there are dynamic assemblies which are generated on the fly dynamically.
Friday, November 27, 2009
Real world examples of abstract classes and interfaces
An abstract class is a class that you cannot create an instance of. It can provide basic functionality, but in order for that functionality to be used, one or more other classes must derive from the abstract class. One of the major benefits of abstract classes is that you can reuse code without having to retype it. That has a plethora of benefits, such as reducing bugs and making coding faster. A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.
Now, an interface is like an abstract class, except it does not contain any logic. Rather, it specifies an interface. So, there might be an interface called IFly. This might have the methods GoForward and GoDown. Those methods would not actually contain any logic... each class that implements interface IFly would have to implement those GoForward and GoDown methods. You could have classes Duck and Finch implement interface IFly. Then, if you want to keep a list of instances that can fly, you just create a list that contains items of type IFly. That way, you can add Ducks and Finches and any other instance of a class the implements IFly to the list.
So, abstract classes can be used to consolidate and share functionality, while interfaces can be used to specify what the common functionality that will be shared between different instances will be, without actually building that functionality for them. Both can help you make your code smaller, just in different ways. There are other differences between interfaces and abstract classes, but those depend on the programming language, so I won't go into those other differences here.
Or
Now, an interface is like an abstract class, except it does not contain any logic. Rather, it specifies an interface. So, there might be an interface called IFly. This might have the methods GoForward and GoDown. Those methods would not actually contain any logic... each class that implements interface IFly would have to implement those GoForward and GoDown methods. You could have classes Duck and Finch implement interface IFly. Then, if you want to keep a list of instances that can fly, you just create a list that contains items of type IFly. That way, you can add Ducks and Finches and any other instance of a class the implements IFly to the list.
So, abstract classes can be used to consolidate and share functionality, while interfaces can be used to specify what the common functionality that will be shared between different instances will be, without actually building that functionality for them. Both can help you make your code smaller, just in different ways. There are other differences between interfaces and abstract classes, but those depend on the programming language, so I won't go into those other differences here.
Or
Do you mean real-world as in "A live software system which includes Abstract classes or interfaces" or do you mean "A contrived example which demonstrates their usefullness"?
If you mean the latter think of
Vehicles could be split into morotized and pedal-powered, but still this is abstract, we still dont know what to do with it.
You could now define a concrete (non-abstract) class, like car.
Intefaces come in handy you can only inherit from one base class. So imagine some vehicles are drivable, others are remote controlled, some vehicles use a stearing wheel, others dont
Now you could derive a DrivableMotorCar from its base clas, and also implement other behaviours.
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
If you mean the latter think of
Vehicle as an abstract class. You can't yet do anything with it because you have no idea what it does, or how to drive it.abstract class Vehicle{} Vehicles could be split into morotized and pedal-powered, but still this is abstract, we still dont know what to do with it.
abstract class MotorVehicle : Vehicle {}abstract class PedaledVehicle : Vehicle {}You could now define a concrete (non-abstract) class, like car.
class MotorCar : MotorVehicle {}Intefaces come in handy you can only inherit from one base class. So imagine some vehicles are drivable, others are remote controlled, some vehicles use a stearing wheel, others dont
interface IDrivable{}interface IHasStearingWheel{} Now you could derive a DrivableMotorCar from its base clas, and also implement other behaviours.
class DrivableMotorCar : MotorVehicle, IDrivable, IHasStearingWheel {}or I Just find a suitable reference... Pls refer to this...
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Deligates Using C#.net
A delegate in C# is similar to a function pointer in C or C++.
Using a delegate allows the programmer to encapsulate a reference to a method inside
a delegate object. The delegate object can then be passed to code which can call the
referenced method, without having to know at compile time which method will be
invoked.
Using a delegate allows the programmer to encapsulate a reference to a method inside
a delegate object. The delegate object can then be passed to code which can call the
referenced method, without having to know at compile time which method will be
invoked.
using System;
namespace Akadia.BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}
http://www.akadia.com/services/dotnet_delegates_and_events.html
Using JavaScript with ASP.Net GridView Control
am explaining how to make use JavaScript in the ASP.Net GridView control and make it more elegant by reducing postbacks.
Functions such as
1. Highlighting selected row
2. Check/Uncheck all records using single checkbox.
3. Highlight row on mouseover event.
The above three functions can be easily achieved using JavaScript thus avoiding postbacks.
To start with I have a GridView control with a header checkbox and checkbox for each individual record
To start with I have a GridView control with a header checkbox and checkbox for each individual record
Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later. Also I have attached a RowDataBound event to the GridView to add mouseover event
Highlight Row when checkbox is checked
The above function is invoked when you check / uncheck a checkbox in GridView row First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked. The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not. If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it Check all checkboxes functionality The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows. And when unchecked it restores back the original color of the row and unchecks the checkboxes. Note: The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all. Highlight GridView row on mouseover event
The above JavaScript function accepts the reference of the GridView Row and the event which has triggered it.
Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.
The above function is called on the mouseover and mouseout events of the GridView row. These events are attached to the GridView Row on the RowDataBound events refer the code below
C#
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
}
}
VB.Net
Protected Sub RowDataBound(ByVal sender As Object,
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)")
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)")
End If
End Sub
You can try out the functionality discussed above using the sample GridView here
CustomerID City Country PostalCode
ALFKI Berlin Germany 12209
ANATR México D.F. Mexico 05021
ANTON México D.F. Mexico 05023
AROUT London UK WA1 1DP
BERGS Luleå Sweden S-958 22
BLAUS Mannheim Germany 68306
BLONP Strasbourg France 67000
BOLID Madrid Spain 28023
BONAP Marseille France 13008
BOTTM Tsawassen Canada T2F 8M4
The above JavaScript functions are tested in the following Browsers
1. Internet Explorer 7
2. Mozilla Firefox 3
3. Google Chrome
http://www.aspsnippets.com/post/2009/03/13/Using-JavaScript-with-ASPNet-GridView-Control.aspx
Functions such as
1. Highlighting selected row
2. Check/Uncheck all records using single checkbox.
3. Highlight row on mouseover event.
The above three functions can be easily achieved using JavaScript thus avoiding postbacks.
To start with I have a GridView control with a header checkbox and checkbox for each individual record
To start with I have a GridView control with a header checkbox and checkbox for each individual record
Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later. Also I have attached a RowDataBound event to the GridView to add mouseover event
Highlight Row when checkbox is checked
The above function is invoked when you check / uncheck a checkbox in GridView row First part of the function highlights the row if the checkbox is checked else it changes the row to the original color if the checkbox is unchecked. The Second part loops through all the checkboxes to find out whether at least one checkbox is unchecked or not. If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it Check all checkboxes functionality The above function is executed when you click the Header check all checkbox When the Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows. And when unchecked it restores back the original color of the row and unchecks the checkboxes. Note: The check all checkboxes checks all the checkboxes only for the current page of the GridView and not all. Highlight GridView row on mouseover event
The above JavaScript function accepts the reference of the GridView Row and the event which has triggered it.
Then based on the event type if event is mouseover it highlights the row by changing its color to orange else if the event is mouseout it changes the row’s color back to its original before the event occurred.
The above function is called on the mouseover and mouseout events of the GridView row. These events are attached to the GridView Row on the RowDataBound events refer the code below
C#
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
}
}
VB.Net
Protected Sub RowDataBound(ByVal sender As Object,
ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)")
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)")
End If
End Sub
You can try out the functionality discussed above using the sample GridView here
CustomerID City Country PostalCode
ALFKI Berlin Germany 12209
ANATR México D.F. Mexico 05021
ANTON México D.F. Mexico 05023
AROUT London UK WA1 1DP
BERGS Luleå Sweden S-958 22
BLAUS Mannheim Germany 68306
BLONP Strasbourg France 67000
BOLID Madrid Spain 28023
BONAP Marseille France 13008
BOTTM Tsawassen Canada T2F 8M4
The above JavaScript functions are tested in the following Browsers
1. Internet Explorer 7
2. Mozilla Firefox 3
3. Google Chrome
http://www.aspsnippets.com/post/2009/03/13/Using-JavaScript-with-ASPNet-GridView-Control.aspx
difference between gridview,data list and repeater control
Explanation:
In ASP .NET basically there are three kinds of the Data
Presentation Controls.
GridView (or DataGrid)
DataList
Repeater
When we talk about usage of one Data Presentation Controls
then many of us get confused about choosing one. When you
need to use one of the data Presentation Control then You
have to see what kind of behavior you need in your Data
Display.
Do you want to show Data in many Pages or in one page?
Do you have to Display more then one column in a Row ?
Do you want to have a Row repeating Possibility?
Will users be able to update, Insert and delete the Data?
We are going provide a list of different abilities of
Repeater Control, Datalist Control and GridView Control.
Features of a GridView
•Displays data as a table
•Control over
–Alternate item
–Header
–Footer
–Colors, font, borders, etc.
–Paging
•Updateable
•Item as row
Features of Repeater
•List format
•No default output
•More control
•More complexity
•Item as row
•Not updateable
Features of DataList
•Directional rendering
•Good for columns
•Item as cell
•Alternate item
•Updateable
Repeater :
It contains Header Template, Item template , alternate
Item template and footer template . it can't support
Selection, editing, sorting and paging. this is read only
and fast.
Datalist :
It contains Header Template, Item template , alternate
Item template , Edit itm template and footer template . it
can't support sorting and paging but support selection and
editing
DataGrid(or GridView) :
It contains Header Template, Item template , alternate Item
template , Edit itm template and footer template . it can
support selection, editing , sorting and paging . Mostly
every developer caught used this control .
In ASP .NET basically there are three kinds of the Data
Presentation Controls.
GridView (or DataGrid)
DataList
Repeater
When we talk about usage of one Data Presentation Controls
then many of us get confused about choosing one. When you
need to use one of the data Presentation Control then You
have to see what kind of behavior you need in your Data
Display.
Do you want to show Data in many Pages or in one page?
Do you have to Display more then one column in a Row ?
Do you want to have a Row repeating Possibility?
Will users be able to update, Insert and delete the Data?
We are going provide a list of different abilities of
Repeater Control, Datalist Control and GridView Control.
Features of a GridView
•Displays data as a table
•Control over
–Alternate item
–Header
–Footer
–Colors, font, borders, etc.
–Paging
•Updateable
•Item as row
Features of Repeater
•List format
•No default output
•More control
•More complexity
•Item as row
•Not updateable
Features of DataList
•Directional rendering
•Good for columns
•Item as cell
•Alternate item
•Updateable
Repeater :
It contains Header Template, Item template , alternate
Item template and footer template . it can't support
Selection, editing, sorting and paging. this is read only
and fast.
Datalist :
It contains Header Template, Item template , alternate
Item template , Edit itm template and footer template . it
can't support sorting and paging but support selection and
editing
DataGrid(or GridView) :
It contains Header Template, Item template , alternate Item
template , Edit itm template and footer template . it can
support selection, editing , sorting and paging . Mostly
every developer caught used this control .
Nesting the DropDownList to Gridview in ASP.NET 2.0(C#)
To nest the DropDownList control to GridView control is very helpful to show the data by selectable criteria. The DropDownList control can be easily nested to the GridView control. In this sample, each DropDownList is binded for different data. For instance, we can use GridView to show each category data in Northwind database, while we can use DropDownList to show all products under the selected category in each line. We will show you this tutorial by ASP.NET 2.0 and C#.
To nest the DropDownList control to GridView control is very helpful to show the data by selectable criteria. The DropDownList control can be easily nested to the GridView control. In this sample, each DropDownList is binded for different content. For instance, we can use GridView to show each category data in northwind database, and we can use DropDownList to show all products under the selected category in each line.
First, to connect to the sample database, you will need to import the System.Data.SqlClient namespace.
The front GridviewNestingDropdowlist.aspx page looks something like this:
The flow for the code behind page is as follows.
using System; using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class GridviewNestingDropdowlist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gridview1.DataSource = getdataset().Tables[0];
gridview1.DataBind();
}
private DataSet getdataset()
{
string connectionstring = "Data Source=localhost;Initial Catalog=northwind;User ID=sa;password=";
string query = "select p.categoryid,p.productid, p.productname,c.categoryid,c.categoryname from products p,categories c where p.categoryid=c.categoryid and c.categoryid<3";
SqlConnection myconnection = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(query, myconnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}
protected void gridview1_rowdatabound(object sender, GridViewRowEventArgs e)
{
DataTable mytable = new DataTable();
DataColumn productidcolumn = new DataColumn("productid");
DataColumn productnamecolumn = new DataColumn("productname");
mytable.Columns.Add(productidcolumn);
mytable.Columns.Add(productnamecolumn);
DataSet ds = new DataSet();
ds = getdataset();
int categoryid = 0;
string expression = string.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
categoryid = Int32.Parse(e.Row.Cells[0].Text);
expression = "categoryid = " + categoryid;
DropDownList ddl = (DropDownList)e.Row.FindControl("dropdownlist1");
DataRow[] rows = ds.Tables[0].Select(expression);
foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["productid"] = row["productid"];
newrow["productname"] = row["productname"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "productname";
ddl.DataValueField = "productid";
ddl.DataBind();
}
}
}
To nest the DropDownList control to GridView control is very helpful to show the data by selectable criteria. The DropDownList control can be easily nested to the GridView control. In this sample, each DropDownList is binded for different content. For instance, we can use GridView to show each category data in northwind database, and we can use DropDownList to show all products under the selected category in each line.
First, to connect to the sample database, you will need to import the System.Data.SqlClient namespace.
The front GridviewNestingDropdowlist.aspx page looks something like this:
The flow for the code behind page is as follows.
using System; using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class GridviewNestingDropdowlist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gridview1.DataSource = getdataset().Tables[0];
gridview1.DataBind();
}
private DataSet getdataset()
{
string connectionstring = "Data Source=localhost;Initial Catalog=northwind;User ID=sa;password=";
string query = "select p.categoryid,p.productid, p.productname,c.categoryid,c.categoryname from products p,categories c where p.categoryid=c.categoryid and c.categoryid<3";
SqlConnection myconnection = new SqlConnection(connectionstring);
SqlDataAdapter ad = new SqlDataAdapter(query, myconnection);
DataSet ds = new DataSet();
ad.Fill(ds);
return ds;
}
protected void gridview1_rowdatabound(object sender, GridViewRowEventArgs e)
{
DataTable mytable = new DataTable();
DataColumn productidcolumn = new DataColumn("productid");
DataColumn productnamecolumn = new DataColumn("productname");
mytable.Columns.Add(productidcolumn);
mytable.Columns.Add(productnamecolumn);
DataSet ds = new DataSet();
ds = getdataset();
int categoryid = 0;
string expression = string.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
categoryid = Int32.Parse(e.Row.Cells[0].Text);
expression = "categoryid = " + categoryid;
DropDownList ddl = (DropDownList)e.Row.FindControl("dropdownlist1");
DataRow[] rows = ds.Tables[0].Select(expression);
foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["productid"] = row["productid"];
newrow["productname"] = row["productname"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "productname";
ddl.DataValueField = "productid";
ddl.DataBind();
}
}
}
Change background color of GridView's Rows
...
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// searching through the rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
bool isnew = (bool)DataBinder.Eval(e.Row.DataItem, "IsNew");
if ( isnew ) e.Row.BackColor = Color.FromName("#FAF7DA"); // is a "new" row
}
}
Difference between BoundField and TemplateField?
Bound field
By using bound field we can bind the data directly by using header text and datafield with out using any controls.
Headertext : we can specify header for the data
Datafield : Its the field which gets the data from dataset.
Example : if we specify a field name in datafield it searches in dataset with the same column name and binds the data.
we can define our own asp controls in bound field column only thing we can do is only binding the data.
Template field
We can define our own asp controls in template field.
and we can bind the data from dataset to template field columns directly.
By using bound field we can bind the data directly by using header text and datafield with out using any controls.
Headertext : we can specify header for the data
Datafield : Its the field which gets the data from dataset.
Example : if we specify a field name in datafield it searches in dataset with the same column name and binds the data.
we can define our own asp controls in bound field column only thing we can do is only binding the data.
Template field
We can define our own asp controls in template field.
and we can bind the data from dataset to template field columns directly.
Row Command Firing twice in GridView Control
I am using a GridView control with a ButtonField and receiving 2 row command
events for each click of the button. Is there a configuration switch that I
can turn that will ensure I only receive one call to my handler? I'm using
the most basic wiring as it comes out of VS 2005.. Thanks in advance for your
help!
ex/
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
Untitled Page
-------------------------------------------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
protected void ApprovalGrid_RowCommand(object sender,
GridViewCommandEventArgs e)
{
// Get the index of the clicked row
int rowindex = Convert.ToInt32(e.CommandArgument);
switch (e.CommandName)
{
case "ApproveEvent":
break;
case "EditEvent":
break;
}
}
}
--
events for each click of the button. Is there a configuration switch that I
can turn that will ensure I only receive one call to my handler? I'm using
the most basic wiring as it comes out of VS 2005.. Thanks in advance for your
help!
ex/
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
-------------------------------------------------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
protected void ApprovalGrid_RowCommand(object sender,
GridViewCommandEventArgs e)
{
// Get the index of the clicked row
int rowindex = Convert.ToInt32(e.CommandArgument);
switch (e.CommandName)
{
case "ApproveEvent":
break;
case "EditEvent":
break;
}
}
}
--
Exporting GridView to Excel
I will show how you can export data from a GridView control to a Microsoft Excel spreadsheet.
Default.aspx
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
private string ConnectionString
{
get { return @"Server=localhost;Database=NorthWind;Trusted_Connection=true"; }
}
protected void BtnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
doubts:Connect To This Link:http://aspalliance.com/771_CodeSnip_Exporting_GridView_to_Excel
http://www.nateirwin.net/2007/04/16/formatting-gridview-control-and-exporting-to-excel/
Default.aspx
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
private string ConnectionString
{
get { return @"Server=localhost;Database=NorthWind;Trusted_Connection=true"; }
}
protected void BtnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
doubts:Connect To This Link:http://aspalliance.com/771_CodeSnip_Exporting_GridView_to_Excel
http://www.nateirwin.net/2007/04/16/formatting-gridview-control-and-exporting-to-excel/
Dynamically Add new row for Grid View Control
private void BindData()
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM tblPerson", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "tblPerson");
GridView1.DataSource = ds;
GridView1.DataBind();
}
Catching the Event Generated by Button Click in the Footer:
As you have already noticed that there is also a Button control inside the Footer of the GridView control. We can easily catch the events and access the TextBox which resides in the Footer.
GridView RowCommand event is generated when ever any event occurs inside the GridView control. This is the best place to catch the Button click event.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
// We are checking against the "ADD"
if (e.CommandName == "ADD")
{
string name = ((TextBox) GridView1.FooterRow.FindControl("txtName")).Text;
AddNewRecord(name);
}
}
Now that we have got the text in the string variable we are ready to insert the new data. The new data is inserted by a small method named AddNewRecord(string name).
private void AddNewRecord(string name)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
string query = @"INSERT INTO tblPerson(Name) VALUES(@Name)";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@Name", name);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
BindData();
}
Wednesday, November 25, 2009
Stored Procedure Using Select Statement
ALTER PROCEDURE [dbo].[getOrderDetails] (@username VARCHAR(50))
AS
BEGIN
SELECT * FROM orders WHERE username = @username;
END
AS
BEGIN
SELECT * FROM orders WHERE username = @username;
END
Stored Procidure For Login
ALTER procedure [dbo].[getlogindata] as
select username,password from customers
select username,password from customers
updating recorde Using StoredProcidures
ALTER proc [dbo].[updatestore]
(
@username varchar(50),
@address varchar(50),
@city varchar(50),
@postalcode varchar(50),
@phone varchar(50),
@emailid varchar(50)
)
as
begin
update stores set
address=@address,
city=@city,
postalcode=@postalcode,
phone=@phone,
emailid=@emailid
where username=@username
end
(
@username varchar(50),
@address varchar(50),
@city varchar(50),
@postalcode varchar(50),
@phone varchar(50),
@emailid varchar(50)
)
as
begin
update stores set
address=@address,
city=@city,
postalcode=@postalcode,
phone=@phone,
emailid=@emailid
where username=@username
end
stored procidure fpr Searching
ALTER proc [dbo].[usp_searchpro]
(
@city varchar(50),
@state varchar(50),
@MaxPrice money,
@minprice money,
@bedrooms int,
@bathrooms int
)
as begin
declare @k money;
select @k= price from Propertyreg where price>@minprice and price<@maxprice
select * from propertyreg where city=@city OR state=@state aND
price=@k and numbedrooms=@bedrooms OR numbathrooms=@bathrooms
end
(
@city varchar(50),
@state varchar(50),
@MaxPrice money,
@minprice money,
@bedrooms int,
@bathrooms int
)
as begin
declare @k money;
select @k= price from Propertyreg where price>@minprice and price<@maxprice
select * from propertyreg where city=@city OR state=@state aND
price=@k and numbedrooms=@bedrooms OR numbathrooms=@bathrooms
end
get Maxid Using Storedprocidure
ALTER PROCEDURE [dbo].[usp_insertProductDetails](
@Product_Name varchar(50),
@Cost varchar(50),
@Description varchar(50),
@UserName varchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ID INT;
SELECT @ID = 1+ ISNULL(MAX(ProductID),0) FROM dbo.Product_Details
INSERT INTO dbo.Product_Details(
ProductID,
Product_Name,
Cost,
Description,
UserName,
Approved)
VALUES(
@ID,
@Product_Name,
@Cost,
@Description,
@UserName,
0
)
END
@Product_Name varchar(50),
@Cost varchar(50),
@Description varchar(50),
@UserName varchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @ID INT;
SELECT @ID = 1+ ISNULL(MAX(ProductID),0) FROM dbo.Product_Details
INSERT INTO dbo.Product_Details(
ProductID,
Product_Name,
Cost,
Description,
UserName,
Approved)
VALUES(
@ID,
@Product_Name,
@Cost,
@Description,
@UserName,
0
)
END
inesrting records Using Stored Procidures
ALTER procedure [dbo].[insertbilling]
(
@ccnumber varchar(50),
@ccexp varchar(50),
@cardholdername varchar(50),
@address varchar(50),
@city varchar(50),
@state varchar(50),
@zip varchar(50),
@username varchar(50)
)
as begin insert into billing values
(
@ccnumber,
@ccexp,
@cardholdername,
@address,
@city,
@state,
@zip,
@username
)
end
(
@ccnumber varchar(50),
@ccexp varchar(50),
@cardholdername varchar(50),
@address varchar(50),
@city varchar(50),
@state varchar(50),
@zip varchar(50),
@username varchar(50)
)
as begin insert into billing values
(
@ccnumber,
@ccexp,
@cardholdername,
@address,
@city,
@state,
@zip,
@username
)
end
Visual Studio 2008 Keyboard Shortcuts
Visual Studio 2008 Keyboard Shortcuts
Here are some extremely helpful keyboard shortcut keys for Visual Studio 2008. You probably know most, but some you won't know. For instance, did you know that Ctrl+. is the same as Sift+Alt+F10?
Note: Some of the shortcuts won't work in all environment configurations (web, C#, etc).
To use, hold down the control key and hit the key combination. Works on the whole document, a specific line, or a selection of code.
Update References/ Add Using Statement (Ctrl +. or Shift +Alt +F10)
I'm referring to the underline that appears under a variable to perform an action like add a using statement, or refacter a method or class name. Not sure what it's called but I use it all the time. Ex: ClassName
List Members (Ctrl +J or Ctrl +K, L)
Displays the autocomplete list for classes, methods, or properties.
List Parameter Info (Ctrl +Shift +Space or Ctrl +K +P)
Lists the parameters for a method. Use this shortcut when your cursor is inside the parenthesis of a method.
Auto Format (Ctrl +K, D or Ctrl +E, D)
Formats C#, VB, ASPX, Javascript, CSS, XML, XSL, and HTML code according to generally accepted formatting standards for the respective programming language. Makes code look nice and neat.
Quick Watch (Ctrl +Alt +Q)
Highlight some code and hit these shortcut keys to display the Quick Watch dialog.
Comment / Uncomment (Ctrl +K, C / Ctrl +K, U)
Comments or uncomments a block of code. Works with C#, VB, ASPX.
Code Bookmarks
Use these to bookmark a line of code. You can cycle through the bookmarks across any file within a project. Bookmarks come in very handy, try it out.
Set/Unset Bookmark (Ctrl +K, K)
Next Bookmark (Ctrl +K, N)
Surround With (Ctrl +S)
Surrounds a block of code with a code snippet.
Build & Debug Shortcuts
Set/Unset Breakpoint (F9)
Build (F6 or Ctrl +Shift +B)
Start Debugging (F5)
Start Without Debugging (Ctrl +F5)
Stop Debugging (Shift +F5)
Continue (F5)
Step Over (F10)
Step Into (F11)
Step Out (Shift +F11)
Here are some extremely helpful keyboard shortcut keys for Visual Studio 2008. You probably know most, but some you won't know. For instance, did you know that Ctrl+. is the same as Sift+Alt+F10?
Note: Some of the shortcuts won't work in all environment configurations (web, C#, etc).
To use, hold down the control key and hit the key combination. Works on the whole document, a specific line, or a selection of code.
Update References/ Add Using Statement (Ctrl +. or Shift +Alt +F10)
I'm referring to the underline that appears under a variable to perform an action like add a using statement, or refacter a method or class name. Not sure what it's called but I use it all the time. Ex: ClassName
List Members (Ctrl +J or Ctrl +K, L)
Displays the autocomplete list for classes, methods, or properties.
List Parameter Info (Ctrl +Shift +Space or Ctrl +K +P)
Lists the parameters for a method. Use this shortcut when your cursor is inside the parenthesis of a method.
Auto Format (Ctrl +K, D or Ctrl +E, D)
Formats C#, VB, ASPX, Javascript, CSS, XML, XSL, and HTML code according to generally accepted formatting standards for the respective programming language. Makes code look nice and neat.
Quick Watch (Ctrl +Alt +Q)
Highlight some code and hit these shortcut keys to display the Quick Watch dialog.
Comment / Uncomment (Ctrl +K, C / Ctrl +K, U)
Comments or uncomments a block of code. Works with C#, VB, ASPX.
Code Bookmarks
Use these to bookmark a line of code. You can cycle through the bookmarks across any file within a project. Bookmarks come in very handy, try it out.
Set/Unset Bookmark (Ctrl +K, K)
Next Bookmark (Ctrl +K, N)
Surround With (Ctrl +S)
Surrounds a block of code with a code snippet.
Build & Debug Shortcuts
Set/Unset Breakpoint (F9)
Build (F6 or Ctrl +Shift +B)
Start Debugging (F5)
Start Without Debugging (Ctrl +F5)
Stop Debugging (Shift +F5)
Continue (F5)
Step Over (F10)
Step Into (F11)
Step Out (Shift +F11)
Generics Concept using LINQ s
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace generics
{
class Program
{
static void Main(string[] args)
{
List mygoObj = new List{
new mygoclass { EmpId = 1, Ename = "raju" },
new mygoclass { EmpId = 2, Ename = "Srinu" },
new mygoclass { EmpId = 3, Ename = "ragu" }
};
var empobj= from c in mygoObj orderby c.Ename select new{total= c.EmpId+c.Ename };
foreach (var item in empobj)
{
Console.WriteLine(item.total);
}
}
}
class mygoclass
{
public int EmpId { get; set; }
public string Ename { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace generics
{
class Program
{
static void Main(string[] args)
{
List
new mygoclass { EmpId = 1, Ename = "raju" },
new mygoclass { EmpId = 2, Ename = "Srinu" },
new mygoclass { EmpId = 3, Ename = "ragu" }
};
var empobj= from c in mygoObj orderby c.Ename select new{total= c.EmpId+c.Ename };
foreach (var item in empobj)
{
Console.WriteLine(item.total);
}
}
}
class mygoclass
{
public int EmpId { get; set; }
public string Ename { get; set; }
}
}
Monday, November 23, 2009
Retrive The Data From Two Tables Using Where Condtion
SELECT employee_number,location_name
FROM tour_locations,tour_expeditions
WHERE tour_locations.location_code = tour_expeditions.location_code
SELECT e1.employee_name
FROM tour_guides e1,tour_guides e2
WHERE e1.hourly_rate=e2.hourly_rate AND
e2.employee_name='Siyabonge Nomvete'
FROM tour_locations,tour_expeditions
WHERE tour_locations.location_code = tour_expeditions.location_code
SELECT e1.employee_name
FROM tour_guides e1,tour_guides e2
WHERE e1.hourly_rate=e2.hourly_rate AND
e2.employee_name='Siyabonge Nomvete'
To Retrive the two fields of data into a single Dropdownlist
sqlcommand cmd=new sqlcommand("select ename+eid as raju from Emp",con);
sqldatareader dr=cmd.excutereader()
{
while(dr.read())
{
ddl.items.add(dr[0]).tostring());
}
}
sqldatareader dr=cmd.excutereader()
{
while(dr.read())
{
ddl.items.add(dr[0]).tostring());
}
}
Thursday, November 19, 2009
Sorting gridview Each Coulmn Using Sorting Technique
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["a"] = e.SortExpression;
GridView1.DataSource = bindgrid();
GridView1.DataBind();
}
DataView dv;
private DataView bindgrid()
{
SqlDataAdapter da1 = new SqlDataAdapter("Select * From enquiry", sqlCon);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
if (ViewState["a"] != null)
{
dv = new DataView (ds1.Tables[0]);
dv.Sort = (string)ViewState["a"];
}
else
{
dv = ds.Tables[0].DefaultView; ;
}
return dv;
}
{
ViewState["a"] = e.SortExpression;
GridView1.DataSource = bindgrid();
GridView1.DataBind();
}
DataView dv;
private DataView bindgrid()
{
SqlDataAdapter da1 = new SqlDataAdapter("Select * From enquiry", sqlCon);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
if (ViewState["a"] != null)
{
dv = new DataView (ds1.Tables[0]);
dv.Sort = (string)ViewState["a"];
}
else
{
dv = ds.Tables[0].DefaultView; ;
}
return dv;
}
Sunday, November 15, 2009
Stored Procedure FOr Inserting Values
ALTER PROCEDURE [dbo].[usp_insertOrderDetails](
@UserName varchar(50),
@ProductName varchar(50),
@Cost varchar(50),
@Description varchar(50),
@Qty varchar(50),
@total varchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.[Order](
UserName,
ProductName,
Cost,
Description,
Qty,
Total,
Order_Date
)
VALUES
(
@UserName,
@ProductName,
@Cost,
@Description ,
@Qty,
@total ,
getdate()
)
END
@UserName varchar(50),
@ProductName varchar(50),
@Cost varchar(50),
@Description varchar(50),
@Qty varchar(50),
@total varchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.[Order](
UserName,
ProductName,
Cost,
Description,
Qty,
Total,
Order_Date
)
VALUES
(
@UserName,
@ProductName,
@Cost,
@Description ,
@Qty,
@total ,
getdate()
)
END
Dynamically Creating Button With Placethe Place holder Container
protected void Page_Load(object sender, EventArgs e)
{
Button bt = new Button();
bt.Height = 20;
bt.Width = 40;
bt.Text = "submit";
PlaceHolder1.Controls.Add(bt);
bt.Click += new EventHandler(bt_Click);
}
{
Button bt = new Button();
bt.Height = 20;
bt.Width = 40;
bt.Text = "submit";
PlaceHolder1.Controls.Add(bt);
bt.Click += new EventHandler(bt_Click);
}
Forgot Password Using Emails
Name Spaces:
using System.Net.Mail;
using System.IO;
using System.Drawing;
We Are Add the Web Reference In solution Explorar
protected void btnOk_Click(object sender, EventArgs e)
{
MailMessage mailMessage = new MailMessage("raju.mygo@gmail.com", txtEmailid .Text );
mailMessage.Subject = "Password Verification";
mailMessage.Body = "Raju";
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("raju.mygo@gmail.com","9959380293");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
btnOk.ForeColor = Color.Red;
btnOk.Text = "password sent Sucessfully to Ur mail Id";
}
using System.Net.Mail;
using System.IO;
using System.Drawing;
We Are Add the Web Reference In solution Explorar
protected void btnOk_Click(object sender, EventArgs e)
{
MailMessage mailMessage = new MailMessage("raju.mygo@gmail.com", txtEmailid .Text );
mailMessage.Subject = "Password Verification";
mailMessage.Body = "Raju";
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("raju.mygo@gmail.com","9959380293");
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
btnOk.ForeColor = Color.Red;
btnOk.Text = "password sent Sucessfully to Ur mail Id";
}
Searching Records Using Like operator
public void binddata()
{
SqlDataAdapter da = new SqlDataAdapter("Select * from enquiry where technologyaw like'" + TextBox1.Text + "%' ", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
{
SqlDataAdapter da = new SqlDataAdapter("Select * from enquiry where technologyaw like'" + TextBox1.Text + "%' ", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
Deleting Records Using Checkbox Control
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
binddata();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count;i++)
{
CheckBox ch = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (ch.Checked == true)
{
Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
con.Open();
SqlCommand cmd = new SqlCommand("delete from colldet where collegeid='" + l1.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
binddata();
}
{
if (!IsPostBack)
{
binddata();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count;i++)
{
CheckBox ch = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (ch.Checked == true)
{
Label l1 = (Label)GridView1.Rows[i].FindControl("Label1");
con.Open();
SqlCommand cmd = new SqlCommand("delete from colldet where collegeid='" + l1.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
binddata();
}
Monday, November 9, 2009
clear All Textboxes code
clear all textboxes in form
protected void Button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in Form.Controls)
{
if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
((TextBox)ctrl).Text = string.Empty;
}
}
masterpage
ContentPlaceHolder content1 = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
foreach (Control ctrl in content1.Controls)
{
if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.Panel")
{
foreach (Control ctr in Panel1.Controls)
{
if (ctr.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
((TextBox)ctr).Text = string.Empty;
}
}
}
foreach (Control c in this.Controls)
{
if (c.GetType().ToString () == "TextBox")
((TextBox)c).Text = string.Empty;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in Form.Controls)
{
if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
((TextBox)ctrl).Text = string.Empty;
}
}
masterpage
ContentPlaceHolder content1 = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
foreach (Control ctrl in content1.Controls)
{
if (ctrl.GetType().ToString() == "System.Web.UI.WebControls.Panel")
{
foreach (Control ctr in Panel1.Controls)
{
if (ctr.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
((TextBox)ctr).Text = string.Empty;
}
}
}
foreach (Control c in this.Controls)
{
if (c.GetType().ToString () == "TextBox")
((TextBox)c).Text = string.Empty;
}
}
Thursday, November 5, 2009
add flash file to asp.net form
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"
style="z-index: 101; left: 3px; width: 427px; position: absolute; top: 140px;
height: 319px">
quality="high" src="hotel1.swf" type="application/x-shockwave-flash" width="800">
Monday, November 2, 2009
Debugging failed because integrated Windows authentication is not enabled
Hi,
in case the project is on local IIS server, you need to enable Integrated
Windows Authentication on the local IIS.
1. Open IIS Manager (Internbet Information Services)
2. Right-click the web site (in case you run it locally you only have
Default web site) and pick Properties
3. Choose "Directory Security" tab and click Edit on "Anonymous access and
authentication control"
4. In the opening window, uncheck "Allow Anonymous access" and check
"Integrated Windows Authentication" (allowing anonymous can make that you
don't have enough permissions to debug)
After that you also need to make sure your NT Debugger user is on Debugger
users group (and in practise to attach to the aspnet_wp.exe process it also
needs to be admin unless you change local security policies)
--
in case the project is on local IIS server, you need to enable Integrated
Windows Authentication on the local IIS.
1. Open IIS Manager (Internbet Information Services)
2. Right-click the web site (in case you run it locally you only have
Default web site) and pick Properties
3. Choose "Directory Security" tab and click Edit on "Anonymous access and
authentication control"
4. In the opening window, uncheck "Allow Anonymous access" and check
"Integrated Windows Authentication" (allowing anonymous can make that you
don't have enough permissions to debug)
After that you also need to make sure your NT Debugger user is on Debugger
users group (and in practise to attach to the aspnet_wp.exe process it also
needs to be admin unless you change local security policies)
--
Subscribe to:
Posts (Atom)