Wednesday, March 24, 2010

SQL InterviewQuestions-Part4

31) What is the difference between stored procedure and a trigger?
a. Storedprocedure
1. We should call it explicitly
2. They can't be inactive
Trigger
1. They can be called automatically inplace of or after (data modifications) triggering actions like Insert, delete or update
2. Thay can be inactive


32) What is normalization?
a. It is a process of organizing data efficiently in database.

33) Advantages of normalization?
a. 1. It reduces redundant data
2. Ensures that data dependencies make sense

34) Why we use join?
a. Joins are used to query data from two or more tables, based on a relationship between certain columns in these tables

35) Types of joins?
a. 1. Join: Returns rows which have match in both the tables
2. Left Join: Returns rows which have match and the rows from the left table which have no match for them in right table
3. Right Join: Returns rows which have match and the rows from the right table which have no match for them in left table
4. Full Join : Returns rows when there is a match in one of the tables

36) why we use Rollback statement?
a. It cancels the proposed changes in a pending database transaction

37) why we use Check constraint?
a. It is used to limit the value range that can be placed in a column

38) why we use NOW() function?
a. It returns the current system date and time

39) What is a subquery?
a. A subquery is a query that appears with in another SQL data manipulation statement

40) Why we use DATEPART() function?
a. It Returns a single part of a date/time

Thursday, February 4, 2010

SQL InterviewQuestions-Part3

21) What is select into command?
a. It selects values from one table and inserts them into another table at the same time
ex: SELECT column1, column2,
INTO table2
FROM table1

22) Why we use DISTINCT command?
a. This is used to return only distinct values. It is used only with Select command.
ex: Select DISTINCT column(s)
From table

23) What are the wild cards?
a. These are used to substitute one or more characters when searching for data in a database
% is used to substitute zero or more characters
[charlist] any single character in charlist
_ substitute for exactly single character
[^charlist] any single character not in list

24) Can we create indexes on views?
a. Yes

25) what is the first index that we can create on a view?
a. It must be unique clustered index

26) what are temporary stored procedures?
a. Temporary stored procedures are like temporary tables and are dropped automatically when you disconnect. They are stored in tempdb and are useful when connected to earlier versions of SQL Server.They can be used when an application builds dynamic t-sql statements that are executed several times.Rather than have the t-sql statements recompiled each time, you can create a temporary stored procedure that is compiled on the first execution and then execute the precompiled plan multiple times.

27) What is referential integrity?
a. It indicates that the relationships between tables have been properly maintained

28) what is Default constraint?
a. It is used to insert default value in to a column

29) How many bytes a currency datatype requires?
a. 8 bytes

30) Can we use Where clause with aggrigate functions?
a. No

Tuesday, January 26, 2010

SQL InterviewQuestions Part2

11) what is a constraint?
a) A constraint is a property which is assigned to a column or set of columns in a table. There are 5 types of constraints
Primary key, Unique key, Foreign Key, Check, Not Null

12) What is an entity integrity?
a) This ensures that there can not be duplicate rows in a table

13) What is a Trigger?
a) A trigger is a special of stored procedure which will be executed
automatically in place of or after data modifications. There are 2 types of triggers
After triggers: This is the trigger which will be executed automatically after the statement which triggered it completes
Instead of Triggers This is the trigger which will be executed automatically in place of triggering statement

14) How many after triggers we can crate for a table?
a) We can create any number of after triggers for each Insert, Update, Delete operations on a table

15) How many Instead of triggers can be created for a table?
a) Only one for each Insert, Delete, Update operations

16) Can a trigger be encrypted?
a) Yes.

17) what is the stored procedure used to set the order of after triggers?
a) sp_settriggerorder

18) can we create after triggers on a view?
a) No

19) what is a view?
a) A view is a virtual table which contains columns from one or more tables.

20) what are the advantages of views?
a) 1. It provides security. means if a view is created on a table then the users can access only those columns which are there in view. they cannot access all the columns
2. It simplifies query execution means a complex query can be stored in the form of a view and view can be accessed using a simple query.

Wednesday, January 20, 2010

SQL InterviewQuestions Part1

1) Differences between Having and Where
Having:
1) It applies to a group as a whole
2) It selects rows afetr grouping
3) It can contain aggrigate functions
4) It is used only in select clause
Where:
1) It applies to individual rows
2) It selects rows before grouping
3) It can't contain aggrigate functions
4) It can be used in select, delete, insert etc

2) What is a primary key?
a) 1)A primary key is used to uniquely identify a row in a table.
2) A table can have only one primary key.
3) It does not allows nulls
4) It creats a clusterd index on a column

3) What is a clustered index?
a) In a clustered index the logical order of index matches the physical
stored order of the rows in a disk. A table can have only one clustered
index. The leaf nodes of clustered index contains the data pages(actual data)

4) What is a transaction and what are its properties?
a) A transaction is a logical unit of work in which all steps must be performed or none. It has 4 main properties
a) Atomicity
b) Consistency
c) Isolation
d) Durability

5) How many non clustered indexes we can create on a table
a) More than one

6) Differences between Union and UnionAll
a) Union:
1) This is used to eliminate duplicate rows
2) This selects only distinct rows
3) It can be used to combine any number of queries
4) It can't contain aggrigate functions
UnionAll:
1) It will not eliminate duplicate rows
2) It selects all the values
3) It can be used to combine maximum of 2 quesries
4) It can contain aggrigate functions

7) What is a composite key?
a) A key formed by combining 2 or more columns is called composite key

8) how many nulls a unique key allows?
a) It allows only one null

9) Differences between Delete and Truncate?
a) Delete:
1) It is a DML statement
2) It can activate a trigger
3) It can include a Where clause
Truncate:
1) It is a DDL statement
2) It cann't activate a trigger
3) It can't include Where clause

10) what is Atomicity?
a) It states that database modifications must follow all or none,
means if a part of a transaction fails then the entire transaction fails.

Wednesday, October 21, 2009

Validating User Credentials

Validating User Credentials
---------------------------------

Let us see how to validate the user credentials(login and password)

In aspx.cs under Button_Click() method write the following code

string email= txtemail.Text;
string password = txtpassword.Text;

SqlConnection con = new SqlConnection(connectionstring);
string str = “select * from UserLoginInfo where email=’ ” + email + “ ‘ and password = ‘ “ + password + “ ‘ “;
SqlCommand cmd = new SqlCommand(str, con);

try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
bool userexists = false;

while(dr.Read())
{
userexists = true;
}
if(userexists)
{
Server.Transfer(“Nextpage.aspx”);
}
else
{
lblresult.Text = “ Please enter the valid email and password”;
}
catch(exception e)
{
throw e;
}
finally
{
con.Close();
}
}

Here we are taking the user entered values(textbox values) into strings and checking them with the values in table UserLoginInfo. If both the values matches then the variable userexists becomes true and you will be derected to another(in this case Nextpage.aspx) page otherwise user will get the message “please enter the valid email and password.

In .aspx page create 2 textboxes for email and password and 1 submit button. In button_click method write the above code.

Wednesday, September 23, 2009

3-Tier Architecture

3-Tier Architecture
-----------------------
Today Iam going to discuss about the 3-Tier Architecture .

PresentationLayer: This is the layer through which user enters the values or values are shown to the user.
BusinessAccessLayer: This layer is used to perform calculations, validations and write business logic.
DataAccessLayer: This layer is used to connect to the database and perform the required actions which may be inserting, deleting, updating values to database or from database.

First create a table with firstname, lastname, age as its columns. Then write a storedprocedure to insert values in to that table.

Then in the project create a class library with the name DataAccessLayer.In this class library create a class with the name UserInformationDAO and write the following code

public class UserInformationDAO
   {
public void InsertUserInfo(string firstname, string lastname, int age)
     {
       SqlConnection con = new SqlConnection(connectionstring);
       SqlCommand cmd = new SqlCommand(“InsertUserData”, con);
       cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(“@firstname” , SqlDbType.Varchar, 30).value = firstname;
cmd.Parameters.Add(“@lastname” , SqlDbType.Varchar, 30).value = lastname;
cmd.Parameters.Add(“@age” , SqlDbType.Int).value = age;

try
       {
         con.Open();
         cmd.ExecuteNonQuery();
       }
catch(Exception e)
       {
         throw e;
       }
finally
       {
         con.Close();
       }
      }
   }

In the above code connectionstring means connection parameters. Which contains servername,databasename, userid, password.
InsertUserData is the name of the storedprocedure to insert values in to the
table. @firstname,@lastname,@age are the storedprocedure variables.Using cmd.Parameters.Add we are adding values to cmd.


Now once again create a class library named BusinessAccessLayer and create a class in that named UserInformationBAO.

public class UserInformationBAO
{
private string firstname;
private string lastname;
private int age;

public string FirstName
       {
          get { return firstname;}
          set { firstname = value;}
       }
public string LastName
       {
           get { return lastname;}
          set { lastname = value;}
       }
public int Age
       {
          get { return age;}
          set { age = value;}
       }

public void InsertUserInfo()
       {
          UserInformationDAO uinfo = new UserInformationDAO()
          uinfo. InsertUserInfo(FirstName, LastName, Age);
       }
}

In the above code we have written 3 properties. In InsertUserInfo method we are creating an object of UserInformationDAO class, using that we are invoking the method InsertUserInfo of UserInformationDAO class.


In .aspx.cs page you need to write the following code to read values from textboxes.

protected void btnsubmit_Click(object sender, EventArgs e)
       {
          UserInformationBAO uinfobao = new UserInformationBAO();

          uinfobao.FirstName = txtfirstname.Text;
          uinfobao.LastName = txtlastname.Text;
          uinfobao.Age = txtage.Text;
          uinfibao.InsertUserInfo();
       }

Here first we are creating an object of UserInformationBAO class and using that object we are reading the values in to properties.

In .aspx page you will have 3 textboxes for firstname, lastname and age. Below these you should create a button so that when this button is clicked values from text boxes will be saved in to database.

<div>
<table>
<tr>
<td>
<asp:Label ID=”lblfirstname” runat= “server”>FirstName </asp:Label>
<asp:Textbox ID=”txtfirstname” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Label ID=”lbllastname” runat= “server” >LastName</asp:Label>
<asp:Textbox ID=”txtlastname” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Label ID=”lblage" runat= “server” >Age</asp:Label>
<asp:Textbox ID=”txtage” runat = “server” ></asp:Textbox>
</td>
</tr>

<tr>
<td>
<asp:Button ID=”btnsubmit” runat= “server” Text = “Submit” OnClick= “btnsubmit_Click”></asp:Button>
</td>
</tr>
</table>
</div>

Tuesday, August 18, 2009

Binding Data to Dropdownlist from Database

Binding Data to Dropdownlist from DataBase
---------------------------------------------------------------
Today Iam going to write on Binding Data to Dropdownlist from Database

Consider that we want to populate the Dropdownlist with a list of countries. For this first we need to create a new .aspx page with the following code

<asp:dropdownlist id =" “dpdcountry”" runat="”server”">
</dropdownlist>

Now create a new classlibrary with the class name DataBinding.cs and write the following code

public class Databinding
{
public static DataTable Execute(string sqlstring)
{
SqlConnection con = new SqlConnection(connectionstring);
DataTable dt = new DataTable(“tb1”);
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt) ;
}
catch(Exception e)
{
throw e;
}
finally
{
con.Close();
}


return dt;
}
}


In the above code Databinding is the class name, Execute is the method which returns a datatable. In the connectionstring you need to specify the 4 parameters of the SqlConnection string.

Now in the .aspx.cs file under Page_Load method you need to write the following the code

If(!IsPostBack)
{
string str = “select country_id , name from Country”;
Datatable dt = Databinding.Execute(str);
dpdcountry.DataValueField = dt.columns[0].ToString();
dpacountry.DataTextField = dt.cloumns[1].ToString();
dpdcountry.DataSource = dt;
dpdcountry.DataBind();
}



On a whole, first we declared a dropdownlist with the name dpdcountry in the .aspx page. Then in .aspx.cs page, in the Page_Load method we are sending the sql string to the class Databinding which connects to the database and returns the data table containg the country names. Then this data table is assigned to the dropdownlist as its datasource. So, when you run this code you get a page with the dropdownlist populated with country names.
Note:
1. You should add the Class Library name in the Referrences of the Project
2. You should use the Class Library name in the directories part of the .aspx.cs page

Thursday, August 6, 2009

C# InterviewQuestions-Part 10

Interview Questions
----------------------
91. How many types of errors are there?
a ) 2 types
1. Run time errors
2. Compile time errors

92. Give some examples of compile time and runtime errors?
a ) Compile time:
missing semocolons
use of undeclared variables
bad references to objects
runtime:
dividing an integer by zero
using negative size for an array
passing a parameter that is not in a valid range

93. What is an exception?
a ) An exception is a condition that occurs by a run time error in the program

94. What is the base class used for all the exceptions in c#?
a ) It is Exception

95. Why do we use throw keyword?
a ) Throw keyword is used to throw our own exceptions.

96. How many exceptions we can write in throws clause?
a ) We can use multiple exceptions.

97. Can a finally block exists with try block but without a catch block?
a ) Yes

98. Can we have nested try blocks in c#?
a ) yes

99. What is the difference between Write() and WriteLine() methods?
a ) Write() method outputs one or more values to the screen without a newline character
WriteLine() method outputs one or more values to the screen with a newline character

100. What is the difference between Read() and Readline() methods?
a ) Read() method returns a single character as int
ReadLine() method returns a string containing a line of text

Monday, July 13, 2009

C# InterviewQuestions- Part 9

81. why we use the ref keyword?
a ) If you want to pass a parameter by reference you should use the keyword ref

82. If an out parameter is not assigned a value with in the body of the function does that method complile?
a ) No. it won't compile

83. How can you make write a read only property?
a ) A property can made a read only by omitting the set accessor from the property defination.

84. When a static constructor is executed?
a ) It is executed when the class is loaded.

85. How many preprocessor directives exists in c#?
a ) They are #define, #undef, #if, #elif, #else, #endif, #error, #warning, #region, #endregion, #pragma etc

86. When an instance constructor is executed?
a ) It is executed when an instance is created.

87. Where you can assign values to a read only field?
a ) We can assign inside a constructor

88. Why we use the sixeof operator?
a ) If we want to know the size of any data type you can use sizeof operator.

89. What are the disadvantages of distructors in c#?
a ) 1. They are non deterministic. means there is no way to know when an object's destructor will actually execute.
2. Implementation of destructor delays the final removal of an object from memory. means objects that have destructors are removed in 2 passes. in the 1st pass only the destructor will be called with out removing object and then the 2nd pass removes the object, which is time taking and which may effect the performance.

90. What is the default access modifier of an interface members?
a) public

Thursday, July 2, 2009

C# InterviewQuestions- Part 8

Interview Questions
-----------------------------

71. Can we declare an abstract method in non abstract class?
a ) No. it can declared only in abstract classes

72. Can we use static or virtual keywords to an abstract method?
a ) No

73. Can an interface extend a class?
a ) No. it can’t extend classes.

74. Is it necessary that the direct base class of a derived class must be at least as accessible as the derived class itself?
a ) Yes.

75. What is the keyword that is used to invoke the constructor method of the super class?
a ) It is the keyword “base”.

76. What is an enumeration?
a ) An enumeration is a user-defined integer type which provides a way for attaching names to numbers.

77. What is boxing?
a ) Conversion of value type to object type (reference type) is known as boxing

78. What is unboxing?
a ) Conversion of object type to value type is known as unboxing.

79. What are the categories of variables that are automatically initialized to their default values?
a ) They are
1. Static variables
2. Instance variables
3. Array elements

80. What is the scope of a variable?
a ) Scope of a variable is the region of code with in which the variable can be accessed.

Tuesday, June 23, 2009

C# InterviewQuestions- Part 7

Interview Questions
----------------------------
61. Can private virtual methods be overridden ?
a ) No. we can not access private methods in inherited classes.

62. Can we inherit multiple interfaces?
a ) yes. In c# multiple inheritance is achieved through interfaces.

63.How can a method be overloaded?
a ) a method can be overloaded by creating a method with the same name but with different parameter order, data types and number

64. Will finally block get executed if the exception had not occurred?
a ) Yes. Finally block always gets executed regardless of an error.

65. Can multiple catch blocks be executed ?
a ) No. once the appropriate catch code is fired control transfer to the finally block then continues with the rest of the code.

66. What is the accessibility level of a protected variable?
a ) It is available to the classes in the same name space.

67. Can you override private virtual methods
a ) No.

68. Can we inherit multiple interfaces?
a) Yes. We can’t inherit multiple classes but we can inherit multiple interfaces.

69. Can we use virtual keyword to a destructor?
a ) No

70. What is the access level of a internal variable?
a ) current assembly

Wednesday, June 10, 2009

C# InterviewQuestions- Part 6

Interview Questions
---------------------------
51. What are the types of strings?
a ) 2 types
1. mutable strings
2. immutable strings

52. Is a string is a reference type or value type?
a ) A string is reference type

53. What do you mean by mutable and immutable ?
a ) Mutable means we can alter the characters contained in them.
Immutable means that we can not alter the characters contained in them

54. What are String and StringBuilder classes?
a ) String class is an immutable class and
StringBuilder class is an mutable class

55. Tell me some methods present in StringBuilder class?
a ) They are
Append(),
Insert(),
Remove(),
Replace(),
appendFormat()

56. What is the namespace of StringBuilder class?
a ) System.Text

57. Tell me some methods present in String class?
a ) They are
Copy(),
Equals(),
ConCat(),
Compare(),
Trim(),
Substring(),

58. Can you store multiple data types in System.Array ?
a ) No.

59. What is the class from which an array is created(derived) automatically in c#
a ) System.Array

60. Some common methods of System.Array class?
a ) Clear(), CpoyTo(), GetValue(), Sort(), Reverse() etc.

Monday, March 9, 2009

C# InterviewQuestions- Part 5

41. How can we achieve multiple inheritance in c#?

a ) Using interfaces.

42. An interface is a value type or reference type?

a ) An interface is a reference type.

43. Does an interface extend classes?

a ) No

44. Can we write constructors and destructors for an interface?

a ) No.

45. What are the default modifiers of members of an interface?

a ) Public and abstract

46. What are the differences between an abstract class and an interface?

a ) Abstract class

1. it can contain implementation to some methods.

2. we can apply access modifiers to one or more methods in an abstract class

3. a class can not inherit more than one abstract class

4. an abstract class can have fields and constants defined

Interface

1. it just contains declarations. No implementation for any method.

2. we can not apply access modifiers to methods inside an interface

3. a class can inherit more than one interface

4. interface does not contain any field definition.

47. Can an interface is implemented by any number of classes?

a ) Yes.

48. What are the types of polymorphism?

a ) 2 types

1. operation polymorphism

2. inclusion polymorphism

49. How we achieve operation polymorphism and inclusion polymorphism?

a ) Operation polymorphism is achieved using overloaded methods and operators

And inclusion polymorphism is achieved using virtual functions.

50. what do you mean by compile time polymorphism?

a ) It is a process of selecting and binding the appropriate method to the object for a particular call at compile time.

Monday, March 2, 2009

C# InterviewQuestions- Part 4

Interview Questions
---------------------------
31. What are the inheritance types?
a ) 1. single level inheritance
2. multi level inheritance
3. multiple inheritance
4. hierarchical inheritance

32. Can we inherit the private members of a class
a ) Yes. But they are not accessible.

33. Why we use the keyword virtual?
a ) When you want to override a method of base class in derived class you should use this virtual keyword to the method in base class

34. Why we use override keyword?
a ) When you want to override a method of base class in derived class you should use this override keyword to the method in derived class

35. What are the abstract classes?
a ) Abstract classes are the classes for which we can not create objects. Means an abstract class can not be instantiated.

36. What are abstract methods?
a ) Abstract methods are the methods which does not contain their body part means they does not provide any implementation.

37. What are the properties of abstract methods?
a ) 1. they do not contain body part.
2. their definition/implementation should be given in non-abstract classes by overriding that method.
3. we can not use static modifier to it.

38. What are the sealed classes?
a ) If you want to prevent a class from being inherited you can use this keyword sealed to that particular class

39. What are sealed methods?
a ) A sealed method is a method which can not be overridden by its derived class.

40. Does a sealed class is an abstract class? Why?
a ) No a sealed class is not an abstract class. Because we can’t inherit a sealed class but we can inherit an abstract class.

Monday, February 23, 2009

C# InterviewQuestions- Part 3

Interview Questions
--------------------------

21. What are the properties of constant members?
a ) 1. They should use the modifier ‘ const’
2. Their value should be given when they are defined (it can’t be changed later)
3. They are implicitly static.

22. Why we use this keyword?
a ) This is used to distinguish local and instant variables that have the same name.

23. Does a copy of a static variable is created every time a class is instantiated?
a ) No.

24. What is a partial class?
a ) A partial class is a class which resides in multiple files. It should use 'partial' keyword. Generally it is used in situations where multiple developers need acess to the same class.

25. What is the name of the class from which all .net classes are derived?
a ) System.Object

26. Does c# support global variables?
a ) No. all declarations must be done inside a class.

27. Differences between property and indexer?
a ) Property
A property can be static member
The get accessor of a property corresponds to a method with no parameters
Indexer
An indexer is always an instant member
The get accessor of an indexer corresponds to the same formal parameter list as the indexer.

28. Differences between overloading and overriding?
a ) Overloading
1. used we want a method with more than one definition with in the same scope
2. in overloading, methods will have same name but different number, types, order of arguments.
Overriding
1. this is used when we have parent, child classes.
2. in overriding , methods will have same name with same arguments and same return type.

29. what is the order of the constructor execution in inheritance?
a ) They are executed from top(parent class) to bottom(child class)

30. what is the order of the destructors execution in inheritance?
a ) They are executed from bottom(child class) to top(parent/base class)

Monday, February 16, 2009

C# InterviewQuestions- Part 2

Interview Questions
---------------------------

11. Can we use access modifier on static constructor?
a ) No

12. How many static constructors we can declare for a single class?
a ) A class can have only one static constructor.

13. What is method overloading?
a ) It is a process of creating methods that have the same name but with different parameter lists and different definitions. This method overloading is used when you want your methods to do same tasks but using different input parameters.

14. What happens when we use ‘private’ modifier to a constructor of a class?
a ) When we declare a constructor of a class as private then we can’t create a objects of that class and we can not use that class as a base class for inheritance

15. Can we overload constructors?
a ) Yes

16. What are instant variables?
a ) Class variables are known as instant variables. Instant variables are different for each object and they are accessed using the objects. When ever a class is instantiated a new copy of the each of the instant variable is created.

17. What are static variables?
a ) These are also known as class variables. Static variables are common for all objects of a class. Only one copy of static variables will be created for all the objects of a class.

18. What are the differences between structure and class
a ) Structure:
It is value type
It is stored on stack
Does not support inheritance
Suitable for small data structure
Class:
It is reference type
It is stored on heap
Supports inheritance
Suitable for complex data structures

19. What is a value type? Give examples
a ) It stores value directly. Value types are stored on stack. Separate memory will be given for each instant of a value type.
Ex: int, float, char, struct

20. What are reference type?
a ) It stores a reference to the value. They are stored on heap.
Ex: class, string, array.

Tuesday, February 10, 2009

C# InterviewQuestions- Part 1

Interview Questions
------------------------

1. What are the main properties of object oriented programming?
a ) There are mainly 3 properties
1. Encapsulation/Abstraction
2. Inheritance
3. Polymorphism

2. What is encapsulation?
a ) This gives a way to hide the internal details of an object from its users.

3. What is inheritance ?
a ) It provides a way to build/create new classes using existing classes.

4. What is polymorphism?
a ) It provides a way to take more than one form.

5. What is a constructor?
a ) Constructor enables an object to initialize itself when it is first created.

6. What are the properties of a constructor?
a ) They are
1. They should have the same name as that of a class
2. They do not specify a return type.
3. we can use access modifiers to constructor.

7. How many types of access modifiers are there ?
a ) 5 types
1. Private
2. Public
3. Protected
4. Internal
5. Protected Internal

8. What access modifiers we can use for a class?
a ) We can use 2 access modifiers
1. Public
2. Internal

9. What is the default access modifier of a class?
a ) It is Internal

10. What is the default access modifier for class members?
a ) It is Private

Tuesday, February 3, 2009

DataSet

Filling dataset with data from more than one table
------------------------------------------------------------
To Fill dataset with data from more than one table from database and to
bind that data to datagrid we need following code

1. In .aspx file you need to write

<div>
<asp:datagrid id="grid1" runat="server" autogeneratecolumns="True">
</asp:datagrid>
<asp:datagrid id="grid2" runat="server" autogeneratecolumns="True">
</asp:datagrid>
</div>

Here we are specifying 2 datagrids to display data from 2 Tables.

2. In .aspx.cs file

1. First we need to open a connection

SqlConnection newconn = new SqlConnection(“Server=xxx;
InitialCatalog=xxx; UserId=xx;Password=xxx”);
Newconn.open();

In the above statement server= xxx means we are specifying server
name.InitialCatalog means database name from which we want to
retrive data. Userid, password are userid and passwords of user
for sql server.

2. Next we need to specify the sql statements(required operation)

DataAdapter da = new SqlDataAdapter("select * from firsttablensme;
Select * from secondtablename”, newconn)

note: here instead of command object we are directly using
DataAdapter.If you want you can use command object also.

In the above statement we are selecting data from two tables.
Newconn is the connection object.

3. Now, we need to fill the dataset

ds = new DataSet();
da.Fill(ds, “firsttablename”);
da.Fill(ds, “secondtablename”);

Here we are using Fill() method of dataadapter to fill the Dataset.

4. Now to bind this data to datagrid we need following code

grid1.DataSource = ds;
grid1.DataSource = ds.Tables[0];
grid1.DataBind();

grid2.DataSource = ds.Tables[1];
grid2.DataBind();

Here DataSource property represents the datasource of the datagrid and
DataBind() method used to bind data to the datagrid.

Note: you can also use caption property of datagrid to specify the table caption
Ex: grid1.caption = “xxx”
here Xxx represents cation for the table displayed by datagrid.

That’s it.

Tuesday, January 27, 2009

Filling data from Database in to Dataset and then to Datagrid

LOADING DATA FROM DATABASE IN TO DATASET AND BINDING IT TO DATAGRID
---------------------------------------------------------------------------------
Dataset can not directly retrieve data from database. For this purpose we should use DataAdapter. DataAdapter acts as a bridge between database and dataset. This is used to retrieve data from Database into Dataset as well as to Update Database through Dataset.It supports insert, delete, update, select operations. It supports disconnected model.

Now we will see the steps required to fill data from database into dataset and then populate that data into datagrid.
For that

In .aspx page, in <div> section we should write
<div>
<asp:datagrid id="exdatagrid" autogeneratecolumns="true" runat="server">
</asp:datagrid>
</div>

Here ID represents the id of the datagrid, runat represents that the datagrid is a server control, AutoGenerateColumns automatically creates the columns for the datagrid.

In the .aspx.cs file

1. First we should open a connection
SqlConnection newconn = new SqlConnection(“Server=xxx;InitialCatalog=xxx;
UserId=xx;Password=xxx”);
Newconn.open();

In the above statement server = xxx means we are specifying server name. InitialCatalog means database name from which we want to retrive data. Userid, password are userid and passwords of user for sql server.

2. Next we need to specify the sql statement(required operation)

SqlCommand cmd = new SqlCommand(“select * from xxx”, newconn);

In this statement first argument specifies the sql select statement(required operation) and second statement specifies the connection object. Here xxx represents Table name in database.

3 Now, we need to declare the DataAdapter

SqlDataAdapter da = new SqlDataAdapter(cmd);

In this statement dataadapter contains the command object as its argument to perform the required operation.

4. Now, we need to fill the dataset

ds = new DataSet();
da.Fill(ds);

In these statements first we declare dataset and then using the Fill() method of dataadapter we fill the dataset with the data from Database.

so now dataset is filled with the data from database.

5. Now we fill datagrid with the information/data in the dataset

exdatagrid.DataSource = ds;
exdatagrid.DataBind();

Here exdatagrid is the id of the datagrid we have declared in .aspx page.
DataSource property represents the datasource(means dataset) for the datagrid. DataBind method is used to bind data to the datagrid.

That’s it. We will see the data populated in to the datagrid.

Tuesday, January 20, 2009

Interview Questions - Part 10

Interview Questions
--------------------------

96. What is a TreeView Server control ?
a ) This is a site navigation control. It displays the data in hierarchical order. Generally is is used to display Menu items for an application. It contains a number of prebuilt styles.

97. What are the differences between viewstate and hidden fields?
a ) Viewstate :
1. This is used for pages that will postback to itself
2. This is a built in structure for maintaining state of a page
3. Security is more as data is hashed, compressed and encoded.
Hiddenfield :
1. This is used for pages that will postback to itself or to another page
2. This is not an inbuilt structure
3. Security is less when compared to viewstate

98. Examples of Navigation controls?
a ) They are
1. TreeView Control
2. Menu
3. SiteMapPath

99. What is the namespace used for web page
a ) System.Web.UI.Page

100. What is the use of IsPostBack method?
a ) This method is to determine whether request is new request or postback request.

101. What are the advantages of DataGrid Control?
a )
1. Inbuilt support for paging and sorting
2. Inbuilt support for user selection and editing
3. Contains its default display