Unit 1: Introduction to .Net Framework
Answer: The .NET Framework is a software development platform created by Microsoft. It provides a comprehensive programming model and a controlled environment for developing, installing, and executing applications on Windows systems.
Main Components:
- CLR (Common Language Runtime): The core execution engine of .NET. It runs the code and provides services that make development easier, such as automatic memory management (Garbage Collection), thread management, exception handling, and security.
- CTS (Common Type System): It establishes a framework that enables cross-language integration. It defines how types are declared, used, and managed in the runtime. Because of CTS, an
intin C# maps exactly to anIntegerin VB.NET, allowing them to communicate. - CLS (Common Language Specification): A subset of the CTS. It is a set of rules and guidelines that languages must follow to interact seamlessly with other .NET languages. For instance, CLS dictates that variable names cannot rely solely on case sensitivity.
- BCL/FCL (Base/Framework Class Library): A massive library of reusable classes, interfaces, and value types organized into namespaces (like
System.IOorSystem.Data). Developers use this library for common tasks like reading files or connecting to databases instead of writing code from scratch.
Code Example (Using the BCL):
using System; // Importing the System namespace from BCL
class Program {
static void Main() {
// Using the Console class from the BCL to print output
Console.WriteLine("Welcome to .NET Framework!");
}
}
Unit 1: Assembly, JIT, Language Basics
Answer: In .NET, source code is not compiled directly into machine code. Instead, it goes through a highly efficient two-stage compilation process.
- Stage 1: Source Code to MSIL (Assembly):
When you compile a C# program, the language-specific compiler translates the source code into a universal language called MSIL (Microsoft Intermediate Language) or simply IL. This MSIL code, along with Metadata (information about the types and references used), is packaged into a file called an Assembly. An assembly is usually a.dll(library) or.exe(executable) file. It is platform-independent at this stage. - Stage 2: MSIL to Machine Code (JIT):
When you run the application, the CLR takes control. The CLR contains a compiler called the JIT (Just-In-Time) Compiler. The JIT reads the MSIL inside the assembly and translates it into the native machine code (0s and 1s) specific to the hardware it is currently running on. It only compiles the parts of the code (methods) that are actually called during execution, saving memory and startup time.
Types of JIT Compilers:
- Pre-JIT: Compiles the entire assembly into native code at install time, completely bypassing runtime compilation.
- Econo-JIT: Compiles methods only when they are called, and then removes them from memory to save space.
- Normal-JIT: (Default) Compiles methods only when they are called the first time, and then caches the native code in memory so subsequent calls execute instantly.
Unit 1: Managed Code and Unmanaged Code
Answer: The distinction between Managed and Unmanaged code lies in who is responsible for executing the program and managing system resources.
- Managed Code:
- Code whose execution is fully managed by the .NET Common Language Runtime (CLR).
- The CLR automatically handles crucial tasks like memory allocation, Garbage Collection (freeing up unused memory), type safety, and security.
- Any code written in C#, VB.NET, or F# compiles into MSIL and runs as managed code.
- Developers do not write explicit code to release memory.
- Unmanaged Code:
- Code that is executed directly by the Operating System, completely outside the boundaries of the .NET CLR.
- The programmer is 100% responsible for memory management, security, and cleaning up resources. If the programmer forgets to free memory, it results in memory leaks.
- Examples include programs written in C, C++, or legacy COM components.
- C# can interact with unmanaged code using P/Invoke or by wrapping code in an
unsafeblock.
Unit 1: Data Types, Boxing and UnBoxing
Answer: In C#, variables are categorized into two main types based on how they store data in memory.
1. Value Types (Stored on the Stack):
These store the actual data directly within their memory location. If you copy a value type to another variable, C# creates an entirely independent copy. Modifying one does not change the other. Examples include int, float, bool, and struct.
2. Reference Types (Stored on the Heap):
These store a reference (or memory address) pointing to the actual data. If you copy a reference type to another variable, both variables point to the exact same memory location. Changing the data through one variable will affect the other. Examples include class, string, and arrays.
Boxing and Unboxing:
Because .NET has a unified type system (everything derives from System.Object), it allows conversion between these two types.
- Boxing: The implicit process of converting a Value Type into a Reference Type (
object). It moves the value from the stack to the heap. - Unboxing: The explicit process of extracting the Value Type back out of the object. It requires a cast and moves the value back to the stack.
Code Example:
int myNumber = 42; // Value type (Stack)
// BOXING: Implicitly converting int to object
object boxedObj = myNumber; // Moved to Heap
// UNBOXING: Explicitly casting object back to int
int unboxedNumber = (int)boxedObj; // Moved to Stack
Unit 1: Arrays
Answer: Arrays in C# are reference types that store a fixed-size collection of elements of the same data type. C# supports three main types of arrays:
- 1. One Dimensional Array: A simple linear list of elements accessed via a single index starting from zero.
- 2. Rectangular (Multidimensional) Array: An array with multiple dimensions forming a perfect grid or matrix. Every row has the exact same number of columns. C# uses commas within the brackets
[,]to define dimensions. - 3. Jagged Array: An "array of arrays." It is a multidimensional array where the inner arrays can have varying lengths. This is highly efficient for memory when a perfect grid is not needed. It uses multiple brackets
[][].
Code Examples:
// 1. One Dimensional Array
string[] days = new string[3] { "Mon", "Tue", "Wed" };
// 2. Rectangular Array (2 rows, 3 columns)
int[,] matrix = new int[2, 3] {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Console.WriteLine(matrix[1, 2]); // Output: 6
// 3. Jagged Array
int[][] jagged = new int[2][]; // Array containing 2 rows
jagged[0] = new int[3] { 10, 20, 30 }; // Row 0 has 3 items
jagged[1] = new int[2] { 40, 50 }; // Row 1 has 2 items
Console.WriteLine(jagged[1][0]); // Output: 40
Unit 1: Loops
Answer: Looping statements allow a block of code to be executed repeatedly until a specific condition is met. C# provides four main types of loops.
- for loop: Used when the exact number of iterations is known before entering the loop.
- while loop: An entry-controlled loop. It checks the condition before executing the block. Used when iterations are unknown.
- do..while loop: An exit-controlled loop. It guarantees that the code block executes at least once before checking the condition.
- foreach loop: The
foreachloop is specifically designed to iterate through collections and arrays cleanly and safely. It automatically moves through every item without requiring a manual index counter. It is strictly read-only; you cannot modify the elements of the collection inside aforeachloop.
Code Examples:
// 1. For Loop Example
for (int i = 1; i <= 3; i++) {
Console.WriteLine("Count: " + i);
}
// 2. Foreach Loop Example
string[] fruits = { "Apple", "Mango", "Banana" };
// Automatically fetches each item in the array
foreach (string item in fruits) {
Console.WriteLine("Fruit: " + item);
}
Unit 2: Methods with "ref" and "out" parameters
Answer: In C#, parameters are normally passed by value (a copy is made). The ref and out keywords are used to pass parameters by reference, meaning any changes made to the parameter inside the method will affect the original variable.
- ref (Reference): The variable must be initialized before it is passed to the method. The method can read and modify the value.
- out (Output): The variable does not need to be initialized before passing. However, the method must assign a value to it before the method completely executes. It is often used when a method needs to return multiple values.
Code Example:
class Program {
// ref example
static void MultiplyByTwo(ref int number) {
number = number * 2;
}
// out example
static void GetDetails(out string name, out int age) {
name = "Manthan"; // Must assign value
age = 20; // Must assign value
}
static void Main() {
// Using ref
int myVal = 10; // MUST be initialized
MultiplyByTwo(ref myVal);
Console.WriteLine(myVal); // Outputs 20
// Using out
string n; int a; // No initialization needed
GetDetails(out n, out a);
Console.WriteLine(n + " is " + a); // Outputs Manthan is 20
}
}
Unit 2: Overloading Constructor, Method and Operator
Answer: Operator Overloading allows you to redefine the way standard C# operators (like +, -, *, ==) work with your own custom user-defined classes or structs.
To overload an operator, you define a method using the operator keyword. The method must be strictly public and static.
Code Example:
class Box {
public int length;
public Box(int l) { length = l; }
// Overloading the '+' operator to add two Box objects together
public static Box operator +(Box b1, Box b2) {
Box newBox = new Box(0);
newBox.length = b1.length + b2.length;
return newBox;
}
}
class Program {
static void Main() {
Box box1 = new Box(10);
Box box2 = new Box(20);
// The '+' operator now works on Box objects!
Box box3 = box1 + box2;
Console.WriteLine(box3.length); // Outputs 30
}
}
Unit 2: Sealed Class & Abstract Class
Answer: Abstract and Sealed classes represent the two opposite ends of inheritance in C#.
- Abstract Class: Declared with the
abstractkeyword. It acts as an incomplete blueprint.
- You cannot create an object (instantiate) of an abstract class.
- It is designed specifically to be inherited by other classes.
- It can contain abstract methods (methods without a body that the child class must implement) as well as regular methods. - Sealed Class: Declared with the
sealedkeyword. It represents a finalized, highly secure class.
- You can create objects of a sealed class.
- It cannot be inherited. No class can derive from a sealed class. It stops the inheritance hierarchy.
Code Example:
// Abstract Class Example
abstract class Vehicle {
public abstract void StartEngine(); // No body
}
class Car : Vehicle {
public override void StartEngine() { Console.WriteLine("Engine Started"); }
}
// Sealed Class Example
sealed class SecurityData {
public string password = "123";
}
// class Hacker : SecurityData { } // ERROR: Cannot inherit from sealed class
Unit 2: Property, Indexer
Answer:
1. Properties:
A property is a member that provides a safe and flexible mechanism to read, write, or compute the value of a private field. Properties use get (to read) and set (to write) accessors. This is the standard way to achieve Encapsulation in C#.
class Employee {
private string name; // Private field (hidden)
// Property (Public)
public string Name {
get { return name; }
set { name = value; } // 'value' contains the assigned data
}
}
// Usage: Employee emp = new Employee(); emp.Name = "Rahul";
2. Indexers:
An indexer allows an object to be indexed in the exact same way as an array. It is created using the this keyword and square brackets []. It is useful when your class manages a list or collection of data internally.
class Team {
private string[] players = new string[5];
// Indexer declaration
public string this[int index] {
get { return players[index]; }
set { players[index] = value; }
}
}
// Usage:
// Team myTeam = new Team();
// myTeam[0] = "Virat"; // Treating the object like an array!
Unit 2: Delegates (Single/Multicasting)
Answer: A Delegate in C# is a type-safe function pointer. It is an object that holds a reference (address) to a method. Instead of calling a method directly, you can call it through the delegate. They are the foundation of events.
- Singlecast Delegate: A delegate that points to exactly one method at a time.
- Multicast Delegate: A delegate that points to multiple methods at the same time. When you invoke the delegate, all the methods it points to are executed one by one. You use the
+=operator to attach methods and-=to detach them.
Code Example:
// 1. Declare the delegate
public delegate void MathOperation(int a, int b);
class Program {
static void Add(int a, int b) { Console.WriteLine("Sum: " + (a + b)); }
static void Sub(int a, int b) { Console.WriteLine("Sub: " + (a - b)); }
static void Main() {
// Singlecast Delegate
MathOperation del = Add;
// Making it Multicast by adding another method
del += Sub;
// Invoking the delegate calls BOTH Add and Sub automatically
del(10, 5);
}
}
Unit 2: Events with Event Delegate
Answer: An Event is a notification mechanism. It allows a class (the Publisher) to notify other classes (the Subscribers) when something specific happens, like a button click or a process finishing.
Events are built on top of delegates. Using the event keyword restricts how outside classes can interact with the delegate. Outside classes can only subscribe (+=) or unsubscribe (-=), but they cannot accidentally clear the invocation list or fire the event themselves.
Code Example:
// 1. Define Delegate
public delegate void ProcessHandler();
class FileDownloader {
// 2. Define Event
public event ProcessHandler DownloadCompleted;
public void StartDownload() {
Console.WriteLine("Downloading...");
// 3. Fire the event if there are subscribers
if (DownloadCompleted != null) {
DownloadCompleted();
}
}
}
class Program {
static void Main() {
FileDownloader fd = new FileDownloader();
// 4. Subscriber attaches to the event
fd.DownloadCompleted += () => Console.WriteLine("Notification: File is ready!");
fd.StartDownload();
}
}
Unit 2: Collections
Answer: Non-generic collections (found in the System.Collections namespace) are dynamic data structures. Unlike standard arrays, they automatically resize themselves. They store data as object types, meaning they can hold mixed data types, but require casting when retrieving data.
- ArrayList: A dynamically resizing array. You can add, remove, or insert items at any position.
Example:ArrayList al = new ArrayList(); al.Add(10); al.Add("Hello"); - HashTable: Stores data in Key-Value pairs. It uses a hash code for the key to ensure extremely fast lookups.
Example:Hashtable ht = new Hashtable(); ht.Add("EmpID", 101); - Stack: Works on the Last-In, First-Out (LIFO) principle (like a stack of plates).
Methods:Push()to add an item to the top,Pop()to remove and return the top item. - Queue: Works on the First-In, First-Out (FIFO) principle (like a line at a ticket counter).
Methods:Enqueue()to add to the back,Dequeue()to remove from the front. - SortedList: Stores Key-Value pairs like a HashTable, but automatically keeps the keys sorted in ascending order.
Unit 3: MessageBox class
Answer: The MessageBox class is used to display a predefined dialog box to the user. It pauses the execution of the application until the user clicks a button on it. It is mostly used to show alerts, errors, or ask for simple confirmations.
The Show() method is overloaded to provide different levels of detail:
- 1. Message only:
MessageBox.Show("Record Saved!"); - 2. Message + Title:
MessageBox.Show("Record Saved!", "Success"); - 3. Message + Title + Buttons: Allows you to define which buttons appear (e.g., OK, OKCancel, YesNo).
MessageBox.Show("Delete?", "Confirm", MessageBoxButtons.YesNo); - 4. Message + Title + Buttons + Icon: Adds an icon to the box (e.g., Error, Information, Warning).
MessageBox.Show("Invalid Data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Capturing the Result:
DialogResult result = MessageBox.Show("Do you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
Application.Exit(); // Closes the app if user clicked 'Yes'
}
Unit 3: Form and properties, Events
Answer:
1. Forms and Properties:
A Form is the fundamental container in Windows Programming. It represents a single window in your application. Important properties include:
Text: The title displayed at the top of the window.BackColor/ForeColor: The background and text colors.Size: The width and height of the form.StartPosition: Where the form appears on the screen when loaded (e.g., CenterScreen).FormBorderStyle: Defines if the window can be resized, minimized, or maximized.
2. Concept of Events and Parameters:
Forms and controls are event-driven. An event is an action (like Load, Click, or MouseHover). When you add an event, C# generates an event handler method with two parameters:
object sender: Holds a reference to the specific control that triggered the event (e.g., which button was clicked).EventArgs e: Contains additional data about the event (like mouse coordinates during a click).
// Example of a Button Click Event
private void btnSubmit_Click(object sender, EventArgs e) {
MessageBox.Show("Button was clicked!");
}
Unit 3: Windows Controls
Answer:
1. CheckBox vs. RadioButton:
- CheckBox: Allows the user to select multiple options from a group. Each CheckBox is independent. Use the
Checkedproperty (true/false) to see if it is ticked. (Example: Selecting hobbies). - RadioButton: Allows the user to select only one option from a group. If you select one, the others automatically uncheck. They must be placed in a container (like a GroupBox) to act as a single group. (Example: Selecting Gender).
2. ListBox vs. ComboBox:
- ListBox: Displays a permanently visible, scrollable list of items. It takes up more space on the screen. The user can select one or multiple items (if
SelectionModeis set to MultiSimple). - ComboBox: A drop-down menu. It saves space by showing only the currently selected item until the user clicks the arrow to reveal the list. It usually allows only single selection.
// Adding items to a ComboBox
cmbCities.Items.Add("Rajkot");
cmbCities.Items.Add("Ahmedabad");
// Getting the selected item
string selected = cmbCities.SelectedItem.ToString();
Unit 3: Panel and GroupBox
Answer: Both Panel and GroupBox are "Container Controls." They are used to group related controls together (like grouping a set of RadioButtons for "Gender"). Moving or hiding the container will move or hide all the controls inside it.
- GroupBox:
- Displays a visible border around the controls.
- Displays a caption (text) at the top using theTextproperty.
- Cannot display scrollbars. If controls exceed the size, they get cut off. - Panel:
- By default, it has no border and no caption text (invisible grouping).
- Can display scrollbars. If you setAutoScroll = true, scrollbars appear when controls go out of bounds.
Unit 3: Dialog Boxes
Answer: Dialog boxes are pre-built windows provided by the OS to perform standard tasks like opening files or picking colors. You display them using the ShowDialog() method.
- ColorDialog: Opens a color palette. Used to let the user select a color (e.g., to change text color).
Code:if (colorDialog1.ShowDialog() == DialogResult.OK) { textBox1.ForeColor = colorDialog1.Color; } - FontDialog: Opens a font selection window to let the user choose font family, style, and size.
Code:if (fontDialog1.ShowDialog() == DialogResult.OK) { textBox1.Font = fontDialog1.Font; } - OpenFileDialog: Opens the standard Windows file explorer, allowing the user to browse and select an existing file. You can restrict file types using the
Filterproperty (e.g., "Text Files|*.txt").
Code:if (openFileDialog1.ShowDialog() == DialogResult.OK) { string path = openFileDialog1.FileName; } - SaveFileDialog: Opens a window letting the user specify a location and name to save a new file.
Unit 3: MDI Concept with MDI Notepad
Answer: MDI (Multiple Document Interface) is an application layout where a single "Parent" window contains multiple "Child" windows inside it. Child windows cannot be dragged outside the boundaries of the Parent window. (Example: Adobe Photoshop or old versions of MS Word).
SDI (Single Document Interface), on the other hand, is like standard Notepad, where every new document opens in a completely separate window.
How to create an MDI Notepad:
- Create the main Form (Parent) and set its
IsMdiContainerproperty toTrue. The background will turn dark gray. - Add a MenuStrip to the Parent form with a "File -> New" option.
- Create a second Form (Child) that contains a large TextArea for typing.
- In the "New" menu click event of the Parent, write code to generate the child form and assign its
MdiParentproperty before showing it.
// Code inside the Parent Form's "File -> New" menu click event:
private void newToolStripMenuItem_Click(object sender, EventArgs e) {
ChildNotepadForm childForm = new ChildNotepadForm();
childForm.MdiParent = this; // 'this' refers to the main container
childForm.Show(); // Opens inside the parent
}
Unit 3: Menu: MenuStrip, ContextMenuStrip, ToolStrip
Answer: Menus provide a structured way for users to navigate application features.
- MenuStrip: This is the standard top-level menu bar seen in almost all Windows applications (e.g., File, Edit, View, Help). You can create drop-down items, add shortcut keys (like Ctrl+C), and add separator lines.
- ContextMenuStrip: This is a pop-up menu that appears only when the user Right-Clicks on a specific control. You create the menu, and then assign it to a control (like a TextBox) using the control's
ContextMenuStripproperty. - ToolStrip: A toolbar usually placed just below the MenuStrip. It contains buttons with icons for quick access to common tasks (like a floppy disk icon for Save, or a printer icon for Print) instead of navigating through the text menus.
Unit 3: Timer, TreeView
Answer:
1. Timer Control:
The Timer is an invisible control used to execute a block of code at regular, repeated intervals.
- Interval property: Sets the time delay in milliseconds (e.g., 1000 = 1 second).
- Enabled property: Starts (true) or stops (false) the timer.
- Tick Event: The code inside this event runs every time the interval passes. Often used for digital clocks, animations, or auto-saving.
2. TreeView Control:
The TreeView control displays a hierarchical, tree-like collection of items (nodes). It is exactly like the folder view in Windows File Explorer.
- Users can expand or collapse nodes to see sub-nodes.
- Nodes Property: Used to add TreeNode objects. You can add Root nodes and then add Child nodes inside those Root nodes.
// Adding nodes via code
TreeNode root = treeView1.Nodes.Add("My Computer");
root.Nodes.Add("Local Disk (C:)");
root.Nodes.Add("Local Disk (D:)");
Unit 4: Database Programming with ADO.NET & Data Providers
Answer: ADO.NET (ActiveX Data Objects .NET) is a core data access technology in the .NET Framework. It provides a rich set of classes to connect Windows or Web applications to various relational databases (like SQL Server, Oracle, or Access) to retrieve, manipulate, and update data.
Data Providers in ADO.NET:
A Data Provider is a set of components specifically designed to communicate with a specific type of database. They provide classes for connecting, executing commands, and retrieving results.
- .NET Framework Data Provider for SQL Server: Specifically optimized for Microsoft SQL Server. It uses the
System.Data.SqlClientnamespace. (Classes:SqlConnection,SqlCommand). - .NET Framework Data Provider for OLE DB: Used for older databases or Access databases. It uses the
System.Data.OleDbnamespace. (Classes:OleDbConnection). - .NET Framework Data Provider for ODBC: Used for connecting to legacy data sources via ODBC drivers. It uses the
System.Data.Odbcnamespace. - .NET Framework Data Provider for Oracle: Designed specifically for Oracle databases. It uses the
System.Data.OracleClientnamespace.
// Example of importing the SQL Server Data Provider
using System.Data.SqlClient;
Unit 4: Connected and Disconnected Architecture
Answer: ADO.NET supports two distinct ways to interact with a database, depending on the application's needs.
- Connected Architecture:
- The connection to the database must remain strictly open while the application reads or manipulates the data.
- It uses aDataReaderto fetch data.
- Data is retrieved in a forward-only, read-only stream, making it extremely fast.
- Best suited for simple data displaying (like filling a dropdown list) where no modifications are needed. - Disconnected Architecture:
- The connection is opened just long enough to fetch the data. The data is copied into a local, in-memory cache called aDataSet, and then the connection is immediately closed.
- The application works with the offline data in theDataSet.
- Once the user finishes making changes (adding/editing/deleting), the connection is re-opened briefly to sync the updates back to the database.
- Best suited for complex desktop applications, working over poor networks, or reducing database server load.
Unit 4: Connected Architecture
Answer:
1. Connection Object (e.g., SqlConnection):
This object is responsible for establishing a physical link to the database. It requires a "Connection String" containing the Server Name, Database Name, and security credentials (username/password or Windows Auth). It uses the Open() and Close() methods.
2. Command Object (e.g., SqlCommand):
Once connected, this object is used to execute SQL queries (SELECT, INSERT, UPDATE, DELETE) or Stored Procedures. It executes using methods like:
ExecuteReader(): For SELECT queries that return rows.ExecuteNonQuery(): For INSERT, UPDATE, DELETE (returns the number of rows affected).ExecuteScalar(): Returns only a single value (like COUNT or SUM).
3. DataReader Object (e.g., SqlDataReader):
It fetches the data from the database one row at a time. It is very fast but strictly read-only and forward-only (you cannot go backward in the data stream).
Code Example (Connected Architecture):
string connString = "Data Source=ServerName;Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
// 1. Open Connection
conn.Open();
// 2. Setup Command
SqlCommand cmd = new SqlCommand("SELECT Name, Age FROM Students", conn);
// 3. Execute and Read Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
// Reading data row by row while connection is open
Console.WriteLine(reader["Name"].ToString() + " - " + reader["Age"].ToString());
}
// 4. Close Connection
reader.Close();
conn.Close();
Unit 4: Disconnected Architecture
Answer:
1. DataAdapter (e.g., SqlDataAdapter):
This acts as the bridge between the physical database and the local disconnected DataSet. It automatically opens the connection, fetches the data using the Fill() method, puts it in the DataSet, and then immediately closes the connection. It also uses the Update() method to push offline changes back to the database.
2. DataSet:
It is an in-memory cache of data. Think of it as a "mini-database" living inside your computer's RAM. It can hold multiple tables, relationships, and constraints, entirely disconnected from the real database server.
3. DataTable, DataRow, and DataColumn:
Inside the DataSet, data is organized into exactly these components:
- DataTable: Represents a single local table (e.g., "Students").
- DataColumn: Represents the columns and their data types (e.g., "ID" as Int, "Name" as String).
- DataRow: Represents the actual records/data inside the table.
Code Example (Disconnected Architecture):
string connString = "Data Source=ServerName;Initial Catalog=MyDatabase;Integrated Security=True";
// 1. Setup DataAdapter with a query
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Students", connString);
// 2. Create an empty DataSet
DataSet ds = new DataSet();
// 3. Use the adapter to FILL the DataSet
// The adapter automatically opens, reads, and closes the connection!
adapter.Fill(ds, "LocalStudentsTable");
// 4. Work with the disconnected DataTable
DataTable dt = ds.Tables["LocalStudentsTable"];
foreach (DataRow row in dt.Rows) {
Console.WriteLine(row["Name"].ToString());
}
Unit 4: DataRelation and DataView
Answer: These are advanced objects used within the Disconnected Architecture (DataSet/DataTable) to manipulate data offline.
1. DataView:
A DataView enables you to create different views of the data stored in a single DataTable. You can use it to filter, sort, or search the data without modifying the underlying table itself (similar to a SQL VIEW). You can bind a DataView directly to UI controls like a GridView.
// Assuming 'dt' is a populated DataTable
DataView view = new DataView(dt);
// Filtering the view offline
view.RowFilter = "Age > 18";
// Sorting the view offline
view.Sort = "Name ASC";
2. DataRelation:
Since a DataSet can hold multiple tables, a DataRelation is used to define parent-child relationships between two DataTables (similar to Primary Key / Foreign Key relationships in SQL). It allows you to easily navigate from a parent record (e.g., a Customer) to all its child records (e.g., their Orders).
// Example: Linking a Customers table to an Orders table locally
DataRelation relation = new DataRelation("CustomerOrders",
ds.Tables["Customers"].Columns["CustID"],
ds.Tables["Orders"].Columns["CustID"]);
ds.Relations.Add(relation);
Unit 4: Data Binding and GridView Programming
Answer:
1. Data Binding:
Data Binding is the process of tying UI controls (like TextBoxes, ComboBoxes, or GridViews) to a data source (like an array, a list, or an ADO.NET DataTable). When the data source changes, the UI automatically updates, and vice versa.
There are two types:
- Simple Binding: Binding a control to a single data value (e.g., binding a TextBox to the "Name" column of a specific row).
- Complex Binding: Binding a control that can display multiple records at once (e.g., binding a ComboBox or GridView to an entire DataTable).
2. GridView Programming (DataGridView):
The DataGridView is a powerful UI control in Windows Forms used to display tabular data in rows and columns. It allows users to view, edit, add, and delete records directly on the screen.
To populate a DataGridView dynamically, you simply assign a fetched DataTable or DataSet to its DataSource property. The grid will automatically generate the required columns and rows.
Code Example (Binding a GridView):
// Assuming 'adapter' is configured and 'dt' is an empty DataTable
SqlDataAdapter adapter = new SqlDataAdapter("SELECT ID, Name, City FROM Employees", connString);
DataTable dt = new DataTable();
// Fetch offline data
adapter.Fill(dt);
// Complex Data Binding to the UI Grid
dataGridView1.DataSource = dt;
// Optional: Formatting the GridView programmatically
dataGridView1.Columns["ID"].Visible = false; // Hide the ID column
dataGridView1.Columns["Name"].HeaderText = "Employee Name"; // Change column title
Unit 5: User Controls (Components)
Answer: A User Control is a custom, reusable graphical component that you create by combining existing Windows Forms controls (like TextBoxes, Buttons, and Labels) into a single, unified control. It inherits from the System.Windows.Forms.UserControl class.
Why use them? If you need the exact same combination of controls (e.g., an Address block with Street, City, and Pincode textboxes) on multiple forms, creating a User Control saves you from redesigning it every time.
Creating a User Control:
- Right-click the project -> Add -> User Control.
- Drag and drop standard controls onto the designer surface.
- Add Properties: You can create custom properties to get or set values inside your control.
- Add Methods: You can define public methods that forms can call to manipulate the control.
- Add Events: You can define custom events that fire when something happens inside your control.
Code Example (Inside the User Control):
public partial class AddressControl : UserControl {
// Custom Property
public string CityName {
get { return txtCity.Text; }
set { txtCity.Text = value; }
}
// Custom Method
public void ClearData() {
txtCity.Clear();
}
// Custom Event
public event EventHandler CityChanged;
private void txtCity_TextChanged(object sender, EventArgs e) {
if (CityChanged != null) {
CityChanged(this, e); // Fire the event
}
}
}
Using the User Control: Once built, the custom control appears in your Visual Studio Toolbox. You simply drag and drop it onto your main Windows Forms just like a standard button.
Unit 5: Crystal Reports & Types of Reports
Answer: Crystal Reports is a popular business intelligence application used to design and generate dynamic, visually appealing reports from a wide range of data sources (like SQL Server, XML, or Excel). It is tightly integrated into Visual Studio, allowing developers to embed reporting capabilities directly into their Windows or Web applications.
Types of Reports in Crystal Reports:
- Standard Report: The most common type. It displays data in a typical row-and-column format (like a list of employees or a sales invoice). It is highly customizable with grouping and sorting.
- Cross-Tab Report: Similar to an Excel Pivot Table. It displays summarized data grouped across both rows and columns. Useful for comparing data, like showing "Sales by Region" across the top and "Sales by Quarter" down the side.
- Mailing Label Report: Specifically designed to print data in a format suitable for mailing labels. You specify the label size and layout, and it automatically formats addresses to fit perfectly on standard sticky label sheets.
- OLAP (Online Analytical Processing) Report: Used to connect to multi-dimensional data cubes (data warehouses) for advanced, high-speed data analysis and mining.
Unit 5: Report Sections
Answer: The Crystal Reports designer is divided into several horizontal bands called "Sections." Understanding these sections is crucial because where you place a field determines how and when it gets printed.
- 1. Report Header: This section prints only once at the very beginning of the entire report. It is typically used for the main Report Title, a company logo, or a cover page.
- 2. Page Header: This section prints at the top of every single page. It is usually used for column headings (e.g., "Employee ID", "Name", "Salary") so readers know what the data columns represent on every page.
- 3. Details: This is the body of the report. It prints once for every single row/record fetched from the database. This is where you place the actual data fields. If your query returns 100 rows, this section will print 100 times.
- 4. Report Footer: This section prints only once at the very end of the entire report (after the last record). It is used for grand totals, summary charts, or closing remarks.
- 5. Page Footer: This section prints at the bottom of every single page. It is perfectly suited for Page Numbers (e.g., "Page 1 of 5") or print dates.
Unit 5: Formula, Special Field and Summary
Answer:
1. Formula Fields:
A Formula Field allows you to perform custom calculations or manipulate data before it is printed. You write formulas using Crystal Syntax or Basic Syntax.
Example: If your database has a "Price" and "Quantity" column, you can create a Formula Field named TotalAmount with the formula: {Table.Price} * {Table.Quantity} and place it in the Details section.
2. Special Fields:
These are pre-defined, built-in system fields provided by Crystal Reports that display useful information without requiring any coding or formulas.
Examples: Print Date, Print Time, Page Number, Total Page Count, Record Number. These are typically dragged and dropped into the Page Header or Page Footer sections.
3. Summary Fields:
Summary Fields are used to perform mathematical aggregations on your data, such as calculating totals, averages, or counts.
Example: You can right-click the "Salary" field and insert a Summary to calculate the Sum. If placed in the Report Footer, it calculates the Grand Total for all employees. If placed in a Group Footer, it calculates the Subtotal for that specific group.
Unit 5: Setup Project & Types of Setup Projects
Answer: A Setup Project is a special type of project in Visual Studio used to package your finished application into an installer file (usually a .msi or setup.exe). This installer allows end-users to easily install your software on their computers, automatically copying files to the right folders, creating start menu shortcuts, and adding registry entries.
Types of Setup Projects:
- 1. Setup Project: The standard choice. Used to create installers for standard Windows Desktop Applications (Windows Forms or Console apps).
- 2. Web Setup Project: Used specifically for web applications. Instead of installing files to a regular folder like "Program Files", it installs them into the Virtual Directory of an IIS (Internet Information Services) Web Server.
- 3. Merge Module Project (.msm): Used to package shared components (like custom DLLs or user controls) that will be shared across multiple different applications. A Merge Module cannot be installed by itself; it must be included inside a larger Setup Project.
- 4. Cab Project (.cab): Creates a Cabinet file. It is a highly compressed archive used primarily to download components over the internet to a web browser.
Unit 5: Creating Setup Project
Answer: To deploy a completed Windows Application to an end-user, you must create a Setup Project. Here are the basic steps in Visual Studio:
- Add the Setup Project: Right-click your Solution in the Solution Explorer -> Select Add -> New Project -> Choose Setup Project (under Setup and Deployment) -> Give it a name (e.g., "MyAppInstaller").
- Add Project Output: The File System Editor will open. Right-click on the "Application Folder" -> Select Add -> Project Output... -> Choose "Primary Output" from your main Windows Application project. This tells the installer to include your compiled
.exeand related DLLs. - Create Shortcuts: Right-click the Primary Output you just added and select Create Shortcut. You can drag this shortcut to the "User's Desktop" folder or "User's Programs Menu" folder in the File System Editor so the user gets icons on their computer.
- Set Properties: Click on the Setup Project in Solution Explorer. In the Properties window, you can set the
Author,Manufacturer, andProductName. - Build the Installer: Right-click the Setup Project and select Build. Visual Studio will compile the files and generate a
setup.exeand a.msifile in the project's Debug/Release folder. You can now distribute these files to your users!
No comments:
Post a Comment