Saturday, December 24, 2011

SQL Server interview questions: - State publisher, distributor and subscriber in “Replication”?

This is the most expected asked SQL Server interview questions during the interview by the interviewer.

Publisher is the one who owns the database and is the main source for data. Publisher identifies what data should be distributed across.

Distributor is a bridge between publisher and subscriber. Distributor gathers all the published data and holds it until it sends it across to all subscriber. So as it is a bridge who sits in between publisher and subscriber, it supports multiple publisher and subscriber concept.

Subscriber is the end source or the final destination to which data has to be transmitted.


                      Figure: - Publisher, Distributor and Subscriber in action

View video on Query Plan, Logical/Physical operators in SQL Server as follows: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Thursday, December 22, 2011

SQL Server interview questions: - Different types of relationship existing in database designing?

This is one of the most favorite SQL Server interview questions asked by the interviewer during the interview.

We have tried to keep answer as simple as we can. So starts the answer as, basically there are three major relationship models: -
  • One-to-one

                      Figure: - One-to-One relationship ER diagram
  • One-to-many
In this many records in one table corresponds to the one record in other table. Example: - Every one customer can have multiple sales. So there exist one-to-many relationships between customer and sales table.

One “Asset” can have multiple “Maintenance”. So “Asset” entity has one-to-many relationship between them as the ER model shows below.


                     Figure: - One-to-Many Relationship ER diagram
  • Many-to-many
In this, one record in one table corresponds to many rows in other table and also vice-versa. For instance :- In a company one employee can have many skills like java , c# etc and also one skill can belong to many employees.

Given below is a sample of many-to-many relationship. One employee can have knowledge of multiple “Technology”. So in order to implement this we have one more table “Employee Technology” which is linked to the primary key of “Employee” and “Technology” table.


                  Figure: - Many-to-Many Relationship ER diagram
Also see the following video on differences between unique key and primary key in SQL Server as follows:-



Visit for more SQL Server interview questions

Regards,

Get more from author’s blog for SQL Server interview questions

Monday, December 19, 2011

.NET interview questions: - Below are simple two classes Class1 creates objects of Class2 and Class2 creates object of Class1, What will happen?

See the following snap code: -

class Class1 
{
 Class2 o = new Class2();
}
class Class2
{
 Class1 o = new Class1();
}

Answer:

Both the classes are creating objects of each other due which the object will pile up in the memory and lead to "StackOverFlowException". Below is the error image which is displayed once the memory is overused.


See the following video on regular expressions along with some practical demonstrations as follows: -



Visit to get more stuff on  interview questions and answers for .NET

Regards,

Also visit for more author’s other blogs on Most asked .NET interview questions

Saturday, December 10, 2011

.NET/ASP.NET interview questions: - While choosing design, when to consider Data grid, data list, or repeater?

This is one of quiet often asked .NET/ASP.NET interview questions so prepare accordingly to answer it to the interviewer.

Many of the developers make a blind choice of choosing data grid directly, but that is not the right way.

Data grid provides ability to allow the end-user to sort, page, and edit its data. However, it comes at a cost of speed. Second, the display format is simple that is in row and columns. Real life scenarios can be more demanding that

With its templates, the Data List provides more control over the look and feel of the displayed data than the Data Grid. It offers better performance than data grid

Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the data binding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the Data Grid and Data List. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. However, repeater does not provide editing features like data grid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls. Repeater is fastest followed by Datalist and finally data grid.

See video on ASP.NET 4.0 web.config transformation as follows: -



Get more fundamentals stuffs on .NET/ASP.NET interview questions

Regards,
More from author’s blogs on .NET/ASP.NET interview questions for interview references

Monday, December 5, 2011

ASP.NET interview questions: - Working of Forms authentication in ASP.NET

Start answering this ASP.NET interview questions as follows: -

In traditional ASP if you are told to create a login page and do authentication you have to do hell lot of custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see in detail what form authentication is.

Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then Forms authentication mechanism sends the user to the login page.

Following are the steps, which defines steps for Forms authentication:-
  • Configure Web.config file with forms authentication. As shown below in the config file you can see we have give the cookie name and loginurl page.
  • Remove anonymous access to the IIS web application, following are changes done to web.config file.
  • Create the login page, which will accept user information. You will have create your login page that is the Login.aspx, which will actually take the user data.
  • Finally a small coding in the login button.
Let us assume that the login page has two textboxes TX name and txtapssword.

Also, import System.Web.Security and put the following code in login button of the page.


See the following video on Single sign-on using forms authentication in ASP.NET as follows: -



Click and see more ASP.NET interview questions

Regards,

Also view author’s other blog on ASP.NET interview questions

Tuesday, November 29, 2011

ADO.NET interview questions: - Elaborate different implementing ways of optimistic locking in ADO.NET.

This is one of the ADO.NET interview questions asked in the interview. Answer this question with the simple steps as follows.

Ways to implement optimistic locking using ADO.NET: -
  • When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
  • Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking.
Update table1 set field1=@test where Last Timestamp=@Current Timestamp
  • Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken.
Update table1 set field1=@test where field1 = @oldfield1value

Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures: -

Also see the following video on Table Scan And Unique key in SQL Server: -



Please click here to see more ADO.NET interview questions

Regards,

Visit Authors blog for more ADO.NET interview questions

Friday, November 25, 2011

.NET interview questions: - Similarities and Differences between Classes and structures.

One of the most likely .NET interview questions asked in the interview, so you should include the following points in your answers.
Similarities between classes and structures: -
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Structures and classes can implement interface.
  • Both of them can have constructors with and without parameter.
Both can have delegates and events.

Key differences are: -
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
Following you can see video on regular expressions with some practical demonstrations: -


Please click here to see more Dotnet interview questions and answers

Regards,

Visit Authors blog for more Most asked .NET interview questions

Saturday, November 19, 2011

.Net Interview questions: - What is GAC, add/remove an assembly from GAC and how do we make choices between 2 versions of the same assembly?

This .NET interview questions will make you remember the basics of .NET if you are senior person in the .NET industry. For the fresher it is still a hiccup so one can start answering the same as follows: -

About GAC: -

GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following situations: -
  • If the application has to be shared among several application which is in the same computer.
  • If the assembly has some special security, requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.
Add/remove an assembly from GAC: -

You can use the ‘GACUTIL’ tool which comes with visual studio. So to register an assembly in to GAC go to “Visual Studio Command Prompt” and type “gacutil –i (assembly name)”, where (assembly name) is the DLL name of the project.

One you have installed the assembly the DLL can be seen in ‘c:\windows\assembly\’ folder.

When we have many DLL’s to be deployed we need to create setup and deployment package using windows installer. So the common way of deploying GAC DLL in production is by using windows installer.

Making choice between two versions of the same assembly in GAC: -

When we have two version of the same assembly in GAC we need to use binding redirect tag and specify the version we want to use in the new version property as shown in the below “app.config” file.




Get ready to see more basics videos of .NET interview questions on Garbage Collector, Gen 0, 1 & 2 as follows: -



Get more fundamentals stuffs on interview questions and answers for .NET
Regards,

More from author’s blogs on Most asked Dotnet interview question for interview references.

Wednesday, November 16, 2011

WCF interview questions: - Using which binding we can build WCF REST?

This is one of the asked WCF interview questions during the interview. So one proceed answer as the following: -

For WCF REST we need to use WebHttpBinding. WebhttpBinding is enabled by as shown in the below code snippet.




Also see our following video on explanation of REST: -


Click and get to see more on WCF Interview questions series.

Regards,

Also visit author’s blog for more WCF interview questions

Saturday, November 12, 2011

SQL Server Interview Question - How do we connect to SQL SERVER, which namespace do we use?

This SQL Server interview questions is more of practical oriented. Below is the code to connect SQL Server, then we will try to understand the same in a more detailed manner.

Private Sub LoadData()
‘ note :- with and end with makes your code more readable
Dim strConnectionString As String
Dim objConnection As New SqlConnection
Dim objCommand As New SqlCommand
Dim objReader As SqlDataReader
Try
‘ this gets the connectionstring from the app.config file.
‘ note if this gives error see where the MDB file is stored 
  in your pc and point to thastrConnectionString = AppSettings.Item
(“ConnectionString”)
‘ take the connectiostring and initialize the connection object
With objConnection
.ConnectionString = strConnectionString
.Open()
End With
objCommand = New SqlCommand(“Select FirstName from Employees”)
With objCommand
.Connection = objConnection
objReader = .ExecuteReader()
End With
‘ looping through the reader to fill the list box
Do While objReader.Read()
lstData.Items.Add(objReader.Item(“FirstName”))
Loop
Catch ex As Exception
Throw ex
Finally
objConnection.Close()
End Try
<appSettings>
<add key=”Connectionstring” value=”Server=ERMBOM1-IT2;User ID=sa;Database=Employees”/>
</appSettings>
 
Note:- Comments in the code do explain a lot but we will again iterate through the 
whole code later. “LoadData” is the main method which loads the data from SQL SERVER. 
Before running this code you have to install SQL SERVER in your machine. As we are dealing 
with SQLCLIENT we need to setup database in SQL SERVER. Depending on computer you will 
also have to change the connectionstring in Web.config file.
 
For setting up the sample SQL table, we can use the DTS import wizard to import the table. See the below figure which is using data source as Microsoft Access. While importing the database author had, give the database name as “Employees”.

Figure: - Loading “Nwind.mdb” in SQL SERVER
 



Figure: - Load only the Employee table.

To make it simple we will only import the employee table as that is the only thing needed in our sample code.

 












Figure: - View of loaded Employee table

Now from interview point of view definitely you are not going to say the whole source code, which is given in the book. Interviewer expects only the broader answer of what are the steps needed to connect to SQL SERVER. For fundamental sake author has explained the whole source code. In short, you have to explain the “Load Data” method in broader way. Following are the steps to connect to SQL SERVER:-

• First imports the namespace “System.Data.SqlClient”.
• Create a connection object as shown in “Load Data” method.

With objConnection
.Connection String = strConnectionString
.Open ()
End With
• Create the command object with the SQL. Also, assign the created connection object to command object and execute the reader.

ObjCommand = New SqlCommand (“Select First Name from Employees”)
With objCommand
.Connection = objConnection
Breeder = .Execute Reader ()
End With
• Finally loop through the reader and fill the list box. If old VB programmers are expecting the move next command it is replaced by Read () which returns true if there is any data to be read. If the .Read () return is false that means that it’s end of data reader and there is no more data to be read.

Do while objReader.Read ()
lstData.Items.Add (objReader.Item (“First Name”))
Loop
• Do not forget to close the connection object.

See the following video on use of SQL Server in SharePoint and use of virtual path provider














More stuffs on SQL Server interview questions for interview preparation.

Regards,

Go to author’s blog for typical other  SQL Server interview questions

Thursday, November 10, 2011

ADO.NET interview questions: - What are the namespaces provided by .NET for data management?


Following are the namespaces provided by .NET for data management:-
System.Data

This namespace has the dataset object which helps us to access data in a data source independent manner.
System.Data.SqlClient:

This namespace has objects which helps us to connect to SQL Server database.
System.Data.OleDB

This namespace has objects which helps us to connect to other databases like Oracle, Access and also SQL Server database.
System.XML

This Contains the basic objects required to create, read, store, write, and manipulate XML documents.














ADO.NET namespaces

See the following video on calling a stored procedure using LINQ: -













Avail from the link more ADO.NET interview questions for preparation.

Regards,

Refer author’s other blog for complete ADO.NET interview questions

Tuesday, November 8, 2011

ADO.NET interview questions: - Different components in ADO.NET.

There are 6 important components in ADO.NET:-
  • Connection: -This object creates a connection to the database. If you want to do any operation on the database you have to first create a connection object.
  • Command: -This object helps us to execute SQL queries against database. Using command object we can execute select, insert, update and delete SQL command.
  • Data reader: - This provides a recordset which can be browsed only in forward direction. It can only be read but not updated. Data reader is good for large number of records where you want to just browse quickly and display it.
  • Dataset object: -This provides a recordset which can be read back and in forward direction. The recordset can also be updated. Dataset is like a in memory database with tables, rows and fields.
  • Data Adapter: -This object acts as a bridge between database and dataset; it helps to load the dataset object.
  • Data View: - This object is used to sort and filter data in Data table of dataset.


                                                     Figure: - ADO.NET architecture

See the following video on Table Scan and Unique key in SQL Server: -



Get more on ADO.NET interview questions

Regards,

For more on ADO.NET interview questions from author’s blog.

Sunday, November 6, 2011

SQL Server interview questions - What is meant by Referential Integrity in SQL Server?


This is one the typical SQL interview questions and also the favorable question of the interviewers, which has been asked in most of the .NET interviews.

Referential Integrity: - Referential Integrity is a DataBase concept that ensures the relationship between tables remains consistent, where one table has a foreign key reference to the other table which is declared as primary key.

In simply words when a relation is maintained between two table’s using primary key and foreign key reference is called as Referential Integrity.

Let’s see a simple demonstration to understand the concept of Referential Integrity.

In order see it practically you just need to follow the following steps.

Step1: - Let’s first create Two Tables like below diagram with respective relationship.
1. Creating a Customer Table.
Query: -
create table Customer
(
CustID int primary key,
CustomerName varchar(50)
);
 
 









In the above table of customer you can see that I have created two columns with one as primary key.
2. Similarly, let’s create second table name as CustomerDetails.

Query: -
create table CustomerDetails 
(CustID int Foreign key references Customer(CustID),
CustDetailsID int primary key,
CustOrders varchar(50)
);
 
 















In the above table of CustomerDetails you can see that I have declared CustID as foreign key references to the Customer (CustId) table.

Step2: - Now, let’s Insert some data to both the table’s.

Query: - Inserting into Customer Table.

insert into dbo.Customer(CustID,CustomerName)values(1,'Kalim')
insert into dbo.Customer(CustID,CustomerName)values(2,'Wasim')
insert into dbo.Customer(CustID,CustomerName)values(3,'Salim')
insert into dbo.Customer(CustID,CustomerName)values(4,'Nadeem')
 













Query: - Inerting into CustomerDetails Table.

insert into dbo.CustomerDetails(CustID ,CustDetailsID ,CustOrders ) 
values(1,1,'Pizza')
insert into dbo.CustomerDetails(CustID ,CustDetailsID ,CustOrders ) 
values(1,2,'Pepsi')
insert into dbo.CustomerDetails(CustID ,CustDetailsID ,CustOrders ) 
values(3,3,'Veg-Roll')
insert into dbo.CustomerDetails(CustID ,CustDetailsID ,CustOrders ) 
values(2,4,'Chicken-Pizza')
 












Note: - When there is Referential Integrity between two table’s then you cannot delete record from the respective table.

Step3: - Let’s see a example to prove the above mentioned note.

So, let’s try to delete record from the Customer table and see what is the output.

Query: -
delete from Customer where CustID = 1
As soon as you click on execute you will output result like below diagram.

 






In the above output result diagram you can clearly see that the compiler does not allow deleting record from the table. Which means that, when there is relation maintains between two table’s using Referential Integrity you cannot delete records from the respective tables.

See the following video on the differences between unique key and primary key as follows: -






Get more on SQL Server interview questions

Regards,

See for author’s other blog on SQL Server interview questions

Friday, November 4, 2011

.NET interview questions: – CAS model under .NET 4.0

Under .NET 4.0 for CAS there are two major changes are brought in: -  •

Permission granting is no more the work of CAS; it’s now the work of the hosting model. In other words CAS is disabled in .NET 4.0 by default. The host will decide what rights to be given to the .NET assembly.

A new security model i.e. Security transparent model is introduced. The security transparent model puts code in to separate compartments/ boxes as per the risk associated. If you know a code can do something wrong you can compartmentalizethe code as ‘Security transparent’ and if you have a code which you trust you can box them in to ‘Security critical’.

CAS Model: -

Security transparent code is the code which you feel is unsafe and security safe critical code is the code which you feel is safe and has full access to the system. Security transparent code cannot call critical code directly, if they have to then they need to go through security safe critical code.

Figure: - .NET 4.0 CAS model 

Also see as detailed video on CAS which explains evidence, permission set & code groups as follows:

 

Get more for  for interview questions and answers for Dotnet complete preparation.

Regards,

Refer author’s other blog for complete Most asked Dotnet interview question

Monday, October 31, 2011

.NET interview questions: - Parse data in Threading.

This is a semi-asked .NET interview questions and has been asked in most of the interviews to check your skills on parsing data in threading.

As a senior developer you would be interested to know how exactly we can parse data in threading.
Below is the code snippet for simple use of threading: -

    class Program
    {
        static void Main(string[] args)
        {
            Thread objThread = new Thread(CallMe);
            objThread.Start();
        }
        public static void CallMe()
        {
            for (int i = 0; i <= 5; i++)
            {
                Console.WriteLine("Threading.......");
                Thread.Sleep(2000);
            }
        }
    }

In the above code snippet you can see that I have created a “CallMe” function which has a for loop and getting executed till the value of “i” is 5 and simply print a line of text to the output screen after every 2 seconds using Thread.Sleep(2000);.

Now, when you execute this above code snippet you will see result like below diagram.


The above code snippet seems to be works fine but what if there is a situation that you want to execute for loop according to the data passed by the Thread.

The data can be parsed in threading by the following two ways

1. You can parse the value by defining object variable.


2. You can use Lambda Expression.

So, let’s take the above point’s one by one try to understand it in better manner.

In order to see it practically you just need to follow the following steps.

Step1: - Create a simple Console Application for that just open Visual Studio >> go to >> File >> New >> Project >> Windows >> Select Console Application.




Step2: - let us first prove the point of passing the data using object variables.

Now, simply just add the below code snippet in to program.cs file of your Console Application.


    class Program
    {
        static void Main(string[] args)
        {
            Thread objThread = new Thread(CallMe);
            //Passing the value 5.
            objThread.Start(5);
        }
        //Created a CallMe function with a Object parameter "k".
        public static void CallMe(object k)
        {
            //creted a int type variable and type caste it.
            int j = (int)k;
            for (int i = 0; i <= j; i++)
            {
                Console.WriteLine("Threading.......");
                Thread.Sleep(2000);
            }
            Console.ReadLine();
        }
    }

Now, just simply execute your console application and will see result like below diagram.


This is how you can parse the data using Object Variables.

Step3: - similarly, let’s take the second point of parsing the data using Lambda Expression.

Now, simply just change your program.cs file code snippet like below code snippet.

    class Program
    {
        static void Main(string[] args)
        {
       //Created a Lambda Expression and parse the value as 7.
           Thread objThread = new Thread(() => CallMe(7));
            objThread.Start();
        }
     //Created a CallMe function with a int parameter "k".
        public static void CallMe(int k)
        {
     //Created a int type variable which hold the value of k.
            int j = k;
            for (int i = 0; i < j; i++)
            {
                Console.WriteLine("Threading.......");
                Thread.Sleep(2000);
            }
            Console.ReadLine();
        }
    }

In the below diagram you can see that how I have used the Lambda Expression in order to 
parse the data in Threading.


Now, when you run your Console Application you will see the result like below diagram.



View the following video on thread, background thread and foreground thread in .NET: -



Click for more Dotnet interview questions and answers

Regards,

Visit for more author’s blog on Most asked Dotnet interview question

Friday, October 28, 2011

ASP.NET interview questions: - Unique Code in ASP.NET.

This is one of the requirements that would come across you many a times while working on .NET projects. Some of the senior developers will find this question very easy but many of the developer friends find it difficult to answer the above question.

So we have tried to give an answer for this ASP. NET interview questions in the practical form as follows: -

So take a small example to see how exactly we can create a Unique Code like C001, C002……., C00n. 
In order to see it practically you just need to follow the following steps: -

Step1: - Create an ASP.NET Web Application for that just open Visual Studio >> go to >>File >> New >> Project >> Web>> Select ASP.NET Empty Web Application. 




Step2: - Now simply just add a Web Form in to your Web Application for that just go to Solution Explorer >> Right click on the Project name>> ADD >> New Item>> Select Web Form.
Step3: - Assume that we have the table of Customer like below diagram.


Step4: - Design your Web Form like below diagram.



Also add a GridView Control to your WebForm.aspx page.


Step5: - This is the most important step for creating Unique Customer code.
Add the below code snippet in to your WebForm.aspx.cs file.
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AutoGenerateCode();
            }
        }
        public void AutoGenerateCode()
        {
            string Unique Code = "";
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand com = new SqlCommand();
            com.CommandText = "select CustCode from Customer where CustomerID in (select max(CustomerID) from Customer)";
            com.Connection = con;
            SqlDataReader objRead = com.ExecuteReader();
            if (objRead.Read())
            {
                UniqueCode = objRead[0].ToString();
                string sd = UniqueCode.Remove(0, 1);
                int sd1 = Int32.Parse(sd) + 1;
                UniqueCode = sd1.ToString();
                if (UniqueCode.Length == 3)
                {
                    UniqueCode = "C" + UniqueCode;
                }
                if (UniqueCode.Length == 2)
                { 
                    UniqueCode = "C" + "0" + UniqueCode; 
                }
                if (UniqueCode.Length == 1)
                {
                    UniqueCode = "C" + "0" + "0" + UniqueCode; 
                }
            }
            else 
            {
                UniqueCode = "C001"; 
            }
            objRead.Close();
            con.Close();
            TextBox3.Text = UniqueCode;
            //The below line will not allow 
            //the user to modify the Unique Code.
            TextBox3.ReadOnly = true;
        }
Once you have done with all the above steps simply run the application and will see the result like below diagram.

In the above code snippet you can clearly see that the Unique Customer Code is been generated.

See the following video on ASP.NET Authentication, Authorization, Principal and Identity objects as follows: -



Visit for more ASP.NET interview questions

Regards,

Get more from author’s blog for ASP.NET interview questions.

Tuesday, October 25, 2011

ADO.NET interview questions: - What are the ways to implement optimistic locking in ADO.NET?

An interesting ADO.NET interview questions mostly asked by the interviewer during an interview. Following are the ways to implement optimistic locking using ADO.NET: -

  • When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
     
  • Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking.
   Update table1 set field1=@test where Last Timestamp=@Current Timestamp
  • Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken.
Update table1 set field1=@test where field1 = @oldfield1value




Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures.

 Know more on UML’s object diagram by viewing the following video: -



For more on ADO.NET interview questions, so click and visit.

Regards,

Author’s more on ADO.NET interview questions.

Saturday, October 22, 2011

ASP.NET interview questions: - How to make GridView Editable, Updateable and Deleteable in ASP.NET?


The process of making GridView Editable, Updateable and Deleteable is almost used in the entire ASP.NET project. So, making GridView Editable, Updateable and Deleteable is one of the most important aspects according to any ASP.NET project.

Let’s create a simple demonstration to understand the concept of making GridView Editable, Updateable and Deleteable in much better manner.

In order to see it practically you just need to follow the following steps.

Step1: - Create a simple ASP.NET Web Application for that just open Visual Studio >>go to >> File >> New >> Project >> Web >> Select ASP.NET Empty Web Application.



Step2: - Now, simply just add a Web Form to your ASP.NET
Empty Web Application for that just go to >> Solution Explorer >> Right Click on the project name >> Add >> New Item >> Select Web Form.


Now, simply just drag and drop GridView to your Web Form and allow the below
properties to true.

1. Allow AutoGenerateEditButton to True.

2. Allow AutoGenerateDeleteButton to True.


Now, as soon as you set the above two properties you will see the GridView like below diagram.


Step3: - Now, let bind the GridView with Data for that just add the below
code snippet in to your WebForm.aspx.cs file.

        //Below variable holds the Connection String.
string str = ConfigurationManager.AppSettings["Connect"];

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

//Created a GridViewData method to bind data to GridView
//from the SQL Server DataBase Table.
public void GridViewData()
{
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "select * from Book";
  com.Connection = con;
  com.ExecuteNonQuery();
  SqlDataAdapter adap = new SqlDataAdapter(com);
  DataSet ds = new DataSet();
  adap.Fill(ds);
  GridView1.DataSource = ds;
  GridView1.DataBind();
}

Step4: - This is the most important step while making GridView Editable, Updateable and Deleteable.

Now, simply just add the below Events of the GridView control in to your
Web Application.

1. OnRowEditing.

2. OnRowCancelingEdit.

3. OnRowUpdating.

4. OnRowDeleting.


Step5: - now, just add the below code snippet to make necessary changes on the respective events of the
GridView control.

1. OnRowEditing add the below code snippet.

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
 {
  GridView1.EditIndex = e.NewEditIndex;
  GridViewData();
  }

2. OnRowCanelingEdit add the below code snippet.

 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
  GridView1.EditIndex = -1;
  GridViewData();
}

3. OnRowDeleting add the below code snippet.

 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  //The below line of code will hold the Cells[1] data of th GridView Control.
  string id = GridView1.Rows[e.RowIndex].Cells[1].Text;
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "delete from Book where Book_Id = '"+id+"'";
  com.Connection = con;
  com.ExecuteNonQuery();
  GridViewData();
 }

4. OnRowUpdating add the below code snippet.

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  string id = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
  string bookname = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;            string author = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
  string price = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
  string quantity = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
  SqlConnection con = new SqlConnection(str);
  con.Open();
  SqlCommand com = new SqlCommand();
  com.CommandText = "update Book set Book_Name='" + bookname + "',Book_Author='" + author + "',Book_Price='" + price + "',Book_Quantity='" + quantity + "' where Book_Id= '" + id + "'";
  com.Connection = con;
  com.ExecuteNonQuery();
  GridViewData();
}

Note: - You can modify your code according to your requirements.

Step6: - Now, let’s run your Web Application and see the respective results.

Let’s first see the result for deleting.


The above diagram is my output of the loaded GridView and note that I am going to delete the
circled row data from the GridView control.

Now, as soon as you click on the delete link will see the result like below diagram.




In the above result of diagram you can see that the data has been deleted.

Similarly, let’s see the result for updating the below circled row data in the
GridView control.


Now, as soon as you click on the edit link you will see something like below diagram.


Now, let’s modify the Book_Author Name as Kalim Shaikh and click on the Update link and see whether the data is updated or not.


In the above output diagram you can clearly see that now the Book_Author name is modified to
Kalim Shaikh.

See the following video on ASP.NET Tracing and instrumentation.



Visit for more ASP.NET interview questions.

Regards,

For more author's blog on ASP.NET interview questions