What is Application Domain?

The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.
Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages.
MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.
AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.
using System;
using System.Runtime.Remoting;

public class CAppDomainInfo : MarshalByRefObject
{
public string GetAppDomainInfo()
{
return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
}
}
public class App
{
public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );
ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );
CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());
string info = adInfo.GetAppDomainInfo();
Console.WriteLine( "AppDomain info: " + info );
return 0;
}
}

40. Which namespace is the base class for .net Class library?

system.object

What is Code Access Security (CAS)?

CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

What is Event - Delegate? Clear syntax for writing a event delegate

The event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code. The delegate can have one or more associated methods that will be called when your code indicates that the event has occurred. An event in one program can be made available to other programs that target the .NET Framework Common Language Runtime.
// keyword_delegate.cs
// delegate declaration
delegate void MyDelegate(int i);
class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}
public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}
public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate with number: {0}.", i);
}
}

What is portable executable (PE)?

The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR. The specification for the PE/COFF file formats is available at
http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx

What is strong name?

A name that consists of an assembly's identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly

What is JIT (just in time)? how it works?

Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler.
Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls.
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed.
As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.

Can I write IL programs directly?

Yes.
assembly MyAssembly {}
.class MyApp {
.method static void Main() {
.entrypoint
ldstr "Hello, IL!"
call void System.Console::WriteLine(class System. Object)
ret
}
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.

What is MSIL, IL?

When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.

Is .NET a runtime service or a development platform?

It's both and actually a lot more. Microsoft .NET includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The .NET frameworks SDK consists of two parts: the .NET common language runtime and the .NET class library. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform.

What are the new features of Framework 1.1 ?

1. Native Support for Developing Mobile Web Applications

2. Enable Execution of Windows Forms Assemblies Originating from the Internet
Assemblies originating from the Internet zone—for example, Microsoft Windows® Forms controls embedded in an Internet-based Web page or Windows Forms assemblies hosted on an Internet Web server and loaded either through the Web browser or programmatically using the System.Reflection.Assembly.LoadFrom() method—now receive sufficient permission to execute in a semi-trusted manner. Default security policy has been changed so that assemblies assigned by the common language runtime (CLR) to the Internet zone code group now receive the constrained permissions associated with the Internet permission set. In the .NET Framework 1.0 Service Pack 1 and Service Pack 2, such applications received the permissions associated with the Nothing permission set and could not execute.

3. Enable Code Access Security for ASP.NET Applications
Systems administrators can now use code access security to further lock down the permissions granted to ASP.NET Web applications and Web services. Although the operating system account under which an application runs imposes security restrictions on the application, the code access security system of the CLR can enforce additional restrictions on selected application resources based on policies specified by systems administrators. You can use this feature in a shared server environment (such as an Internet service provider (ISP) hosting multiple Web applications on one server) to isolate separate applications from one another, as well as with stand-alone servers where you want applications to run with the minimum necessary privileges.

4. Native Support for Communicating with ODBC and Oracle Databases

5. Unified Programming Model for Smart Client Application Development
The Microsoft .NET Compact Framework brings the CLR, Windows Forms controls, and other .NET Framework features to small devices. The .NET Compact Framework supports a large subset of the .NET Framework class library optimized for small devices.

6. Support for IPv6
The .NET Framework 1.1 supports the emerging update to the Internet Protocol, commonly referred to as IP version 6, or simply IPv6. This protocol is designed to significantly increase the address space used to identify communication endpoints in the Internet to accommodate its ongoing growth.
http://msdn.microsoft.com/netframework/technologyinfo/Overview/whatsnew.aspx

What is CLR, CTS, CLS?

The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture", http://msdn.microsoft.com/net/ecma/

What is .NET Framework?

The .NET Framework has two main components: the common language runtime and the .NET Framework class library.
You can think of the runtime as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that ensure security and robustness.
The class library, is a comprehensive, object-oriented collection of reusable types that you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.

how to use the Char2Format Structure in VB .NET for Highlighting Text

Example

Private Sub SetCharFormatColour(ByVal RichTextBox As RichTextBox)
'Set-up Char2Format2 Structure
Dim CF2 As WinAPI.RichEditControl.CharFormat2
With CF2
.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(CF2)
.dwMask = WinAPI.RichEditControl.CFM_COLOR
.crTextColor = RGB(255, 0, 0)
End With
Dim Win32Error As Integer
Win32Error = WinAPI.RichEditControl.SendMessageA(RichTextBox.Handle.ToInt32, WinAPI.RichEditControl.EM_SETCHARFORMAT, WinAPI.RichEditControl.SCF_SELECTION, CF2)
'If the operation fails, the return value is zero. So lets get the error description and display it.
If Win32Error = 0 Then
MsgBox(WinAPI.General.GetLastErrorMessageDescription)
End If
End Sub

The latter routine requires the following unit in order to provide the interface to the Windows API:

Option Strict On
Imports System.Runtime.InteropServices

Namespace WinAPI
Public Class General
Public Const WM_USER As Int32 = &H400
Public Const WM_SETREDRAW As Int32 = &HB

'Declare Function SendMessageByString Lib "user32" Alias "SendMessageA" _
' (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long

' Declare Function SendMessageByLong Lib "user32" Alias "SendMessageA" _
' (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Declare Auto Function SendMessage Lib "user32" _
(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr

Private Declare Auto Function FormatMessage Lib "kernel32" Alias "FormatMessageA" (ByVal dwFlags As Integer, ByRef lpSource As Object, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByVal lpBuffer As String, ByVal nSize As Integer, ByRef Arguments As Integer) As Integer

Public Shared Function GetLastErrorMessageDescription() As String
Const FORMAT_MESSAGE_FROM_SYSTEM As Short = &H1000S
Const LANG_NEUTRAL As Short = &H0S
Dim Win32Error As Integer
Win32Error = System.Runtime.InteropServices.Marshal.GetLastWin32Error()
Dim Buffer As String = Space(999)
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, Win32Error, LANG_NEUTRAL, Buffer, 999, 0)
Return Trim(Buffer)
End Function
End Class

Public Class RichEditControl
Public Declare Function SendMessageA Lib "user32.dll" _
(ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As CharFormat2) As Integer

Public Structure CharFormat2
Public cbSize As Int32
Public dwMask As Int32
Public dwEffects As Int32
Public yHeight As Int32
Public yOffset As Int32
Public crTextColor As Int32
Public bCharSet As Byte
Public bPitchAndFamily As Byte
Public szFaceName As String
Public wWeight As Int16
Public sSpacing As Int16
Public crBackColor As Int32
Public lcid As Int32
Public dwReserved As Int32
Public sStyle As Int16
Public wKerning As Int16
Public bUnderlineType As Byte
Public bAnimation As Byte
Public bRevAuthor As Byte
Public bReserved1 As Byte
End Structure

Public Declare Function SendMessageAv Lib "user32.dll" Alias "SendMessageA" _
(ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByRef lParam As CharRange) As Integer

Public Structure CharRange
Public cpMin As Int32
Public cpMax As Int32
End Structure

'RichEdit messages
Public Const EM_GETLIMITTEXT As Int32 = General.WM_USER + 37
Public Const EM_POSFROMCHAR As Int32 = General.WM_USER + 38
Public Const EM_CHARFROMPOS As Int32 = General.WM_USER + 39
Public Const EM_SCROLLCARET As Int32 = General.WM_USER + 49
Public Const EM_CANPASTE As Int32 = General.WM_USER + 50
Public Const EM_DISPLAYBAND As Int32 = General.WM_USER + 51
Public Const EM_EXGETSEL As Int32 = General.WM_USER + 52
Public Const EM_EXLIMITTEXT As Int32 = General.WM_USER + 53
Public Const EM_EXLINEFROMCHAR As Int32 = General.WM_USER + 54
Public Const EM_EXSETSEL As Int32 = General.WM_USER + 55
Public Const EM_FINDTEXT As Int32 = General.WM_USER + 56
Public Const EM_FORMATRANGE As Int32 = General.WM_USER + 57
Public Const EM_GETCHARFORMAT As Int32 = General.WM_USER + 58
Public Const EM_GETEVENTMASK As Int32 = General.WM_USER + 59
Public Const EM_GETOLEINTERFACE As Int32 = General.WM_USER + 60
Public Const EM_GETPARAFORMAT As Int32 = General.WM_USER + 61
Public Const EM_GETSELTEXT As Int32 = General.WM_USER + 62
Public Const EM_HIDESELECTION As Int32 = General.WM_USER + 63
Public Const EM_PASTESPECIAL As Int32 = General.WM_USER + 64
Public Const EM_REQUESTRESIZE As Int32 = General.WM_USER + 65
Public Const EM_SELECTIONTYPE As Int32 = General.WM_USER + 66
Public Const EM_SETBKGNDCOLOR As Int32 = General.WM_USER + 67
Public Const EM_SETCHARFORMAT As Int32 = General.WM_USER + 68
Public Const EM_SETEVENTMASK As Int32 = General.WM_USER + 69
Public Const EM_SETOLECALLBACK As Int32 = General.WM_USER + 70
Public Const EM_SETPARAFORMAT As Int32 = General.WM_USER + 71
Public Const EM_SETTARGETDEVICE As Int32 = General.WM_USER + 72
Public Const EM_STREAMIN As Int32 = General.WM_USER + 73
Public Const EM_STREAMOUT As Int32 = General.WM_USER + 74
Public Const EM_GETTEXTRANGE As Int32 = General.WM_USER + 75
Public Const EM_FINDWORDBREAK As Int32 = General.WM_USER + 76
Public Const EM_SETOPTIONS As Int32 = General.WM_USER + 77
Public Const EM_GETOPTIONS As Int32 = General.WM_USER + 78
Public Const EM_FINDTEXTEX As Int32 = General.WM_USER + 79
Public Const EM_GETWORDBREAKPROCEX As Int32 = General.WM_USER + 80
Public Const EM_SETWORDBREAKPROCEX As Int32 = General.WM_USER + 81
'Richedit v2.0 messages
Public Const EM_SETUNDOLIMIT As Int32 = General.WM_USER + 82
Public Const EM_REDO As Int32 = General.WM_USER + 84
Public Const EM_CANREDO As Int32 = General.WM_USER + 85
Public Const EM_GETUNDONAME As Int32 = General.WM_USER + 86
Public Const EM_GETREDONAME As Int32 = General.WM_USER + 87
Public Const EM_STOPGROUPTYPING As Int32 = General.WM_USER + 88
Public Const EM_SETTEXTMODE As Int32 = General.WM_USER + 89
Public Const EM_GETTEXTMODE As Int32 = General.WM_USER + 90

Public Const CFM_BOLD As Int32 = &H1
Public Const CFM_ITALIC As Int32 = &H2
Public Const CFM_UNDERLINE As Int32 = &H4
Public Const CFM_STRIKEOUT As Int32 = &H8
Public Const CFM_PROTECTED As Int32 = &H10
Public Const CFM_LINK As Int32 = &H20
Public Const CFM_SIZE As Int32 = &H80000000
Public Const CFM_COLOR As Int32 = &H40000000
Public Const CFM_FACE As Int32 = &H20000000
Public Const CFM_OFFSET As Int32 = &H10000000
Public Const CFM_CHARSET As Int32 = &H8000000

Public Const SCF_SELECTION As Int32 = &H1
Public Const SCF_WORD As Int32 = &H2
Public Const SCF_DEFAULT As Int32 = &H0
Public Const SCF_ALL As Int32 = &H4
Public Const SCF_USEUIRULES As Int32 = &H8

'Event notification masks
Public Const ENM_NONE As Int32 = &H0
Public Const ENM_CHANGE As Int32 = &H1
Public Const ENM_UPDATE As Int32 = &H2
Public Const ENM_SCROLL As Int32 = &H4
Public Const ENM_KEYEVENTS As Int32 = &H10000
Public Const ENM_MOUSEEVENTS As Int32 = &H20000
Public Const ENM_REQUESTRESIZE As Int32 = &H40000
Public Const ENM_SELCHANGE As Int32 = &H80000
Public Const ENM_DROPFILES As Int32 = &H100000
Public Const ENM_PROTECTED As Int32 = &H200000
Public Const ENM_CORRECTTEXT As Int32 = &H400000 ' PenWin specific
Public Const ENM_SCROLLEVENTS As Int32 = &H8
Public Const ENM_DRAGDROPDONE As Int32 = &H10
Public Const ENM_PARAGRAPHEXPANDED As Int32 = &H20
End Class

End Namespace

Source Code for Print An Array of Strings

Public Class PrintArrayOfStrings
Private pArrayOfStrings() As String
Private pPrintFont As Font
Private pCurrentLine As Integer = 0
Private pArrayOfStrings_UpperBound As Integer

Public Sub New(ByVal ArrayOfStrings() As String)
Me.New(ArrayOfStrings, New Font("Arial", 10))
End Sub

Public Sub New(ByVal ArrayOfStrings() As String, ByVal PrintFont As Font)
pArrayOfStrings = ArrayOfStrings
pPrintFont = PrintFont
pArrayOfStrings_UpperBound = pArrayOfStrings.GetUpperBound(0)
Try
Dim PrintDocument As PrintDocument = New PrintDocument() 'Assumes default printer
AddHandler PrintDocument.PrintPage, New System.Drawing.Printing.PrintPageEventHandler(AddressOf PrintPage)
PrintDocument.Print()
Catch ex As Exception
MessageBox.Show("An error occurred printing. " + ex.Message)
End Try
End Sub

Private Sub PrintPage(ByVal sender As Object, ByVal ev As System.Drawing.Printing.PrintPageEventArgs)
Dim LinesPerPage As Single
Dim yPos As Single = 0
Dim Count As Integer = 0
Dim Line As String
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
LinesPerPage = ev.MarginBounds.Height / pPrintFont.GetHeight(ev.Graphics)
' Print each line of the file.
While (Count < LinesPerPage) And (pCurrentLine <= pArrayOfStrings_UpperBound)
Line = pArrayOfStrings(pCurrentLine)
yPos = topMargin + Count * pPrintFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(Line, pPrintFont, Brushes.Black, leftMargin, yPos, New StringFormat())
Count += 1
pCurrentLine += 1
End While
ev.HasMorePages = (pCurrentLine <= pArrayOfStrings_UpperBound)
End Sub

End Class

how to get Version Information From The AssemblyInfo File in vb.net

Function GetVersion() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart
End With
End Function

Function GetComments() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .Comments
End With
End Function

How to programmatically Resizing DataGrid Columns in vb.net/c#

Public Class MyUtils_DataGrid
'Method: DataGridApplyAutomaticWidths
'Parameters
' DataGrid=DataGrid that is to be formatted.
' NumberOfRowsToScan=Number of data records to be scanned in order to compute the columns widths (Recommend 20).
' MaxPixelWidth=Maximum allowable pixel width of a column.
'
'Takes a DataGrid that should be already assigned a populated dataset,
'and formats the DataGrid so that the column widths reflect the widths of the data.
'This is accomplished by dynamically creating a single DataGridTableStyle and multiple DataGridTextBoxColumn(s).
'For each data column, the width of the column is set to the highest data width within the column.
'In order to reduce computation time where large datasets exist,
'a parameter exists to define how many rows are scanned.
'I would suggest that only the first 20 rows are scanned,
Public Shared Function DataGridApplyAutomaticWidths _
(ByVal DataGrid As System.Windows.Forms.DataGrid, ByVal NumberOfRowsToScan As Integer, ByVal MaxPixelWidth As Integer) _
As DataGridTableStyle
'Create graphics object for measuring widths.
Dim Graphics As Graphics = DataGrid.CreateGraphics()
'Define new table style.
Dim TableStyle As DataGridTableStyle = New DataGridTableStyle()
Try
Dim DataTable As DataTable
'DataTable = DataGrid.DataSource.DataSet.Tables(0)
DataTable = DataGrid.DataSource.Tables(0)
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan, DataTable.Rows.Count)
'Clear any existing table styles.
DataGrid.TableStyles.Clear()
'Use mapping name that is defined in the data source.
TableStyle.MappingName = DataTable.TableName
'Now create the column styles within the table style.
Dim Column As DataColumn
Dim ColumnStyle As DataGridTextBoxColumn
Dim Width As Integer
For Each Column In DataTable.Columns
ColumnStyle = New DataGridTextBoxColumn()
With ColumnStyle
.TextBox.Enabled = True
.HeaderText = Column.ColumnName
.MappingName = Column.ColumnName
'Set width to header text width.
Width = Graphics.MeasureString(.HeaderText, DataGrid.Font, MaxPixelWidth).Width
End With
'Change width, if data width is wider than header text width.
'Check the width of the data in the first X rows.
Dim iRow As Integer
Dim DataRow As DataRow
For iRow = 0 To NumberOfRowsToScan - 1
DataRow = DataTable.Rows(iRow)
If Not IsDBNull(DataRow(Column.ColumnName)) Then
Width = System.Math.Max(Width, Graphics.MeasureString(DataRow(Column.ColumnName), DataGrid.Font, MaxPixelWidth).Width)
End If
Next
ColumnStyle.Width = Width + 4
'Add the new column style to the table style.
TableStyle.GridColumnStyles.Add(ColumnStyle)
Next
'Add the new table style to the data grid.
DataGrid.TableStyles.Add(TableStyle)
Finally
Graphics.Dispose()
End Try
Return TableStyle
End Function

'This one allows a DataGridTableStyle to all ready exist on the table.
Public Shared Function DataGridApplyAutomaticWidths _
(ByVal DataGrid As System.Windows.Forms.DataGrid, ByVal TableStyle As DataGridTableStyle, _
ByVal NumberOfRowsToScan As Integer, ByVal MaxPixelWidth As Integer) _
As DataGridTableStyle
'Create graphics object for measuring widths.
Dim Graphics As Graphics = DataGrid.CreateGraphics()
Try
Dim DataTable As DataTable
'DataTable = DataGrid.DataSource.DataSet.Tables(0)
DataTable = DataGrid.DataSource.Tables(0)
'Can only scan rows if they exist.
NumberOfRowsToScan = System.Math.Min(NumberOfRowsToScan, DataTable.Rows.Count)
'Now loop through the columns and set the widths.
Dim Column As DataColumn
Dim ColumnStyle As DataGridColumnStyle
Dim Width As Integer
For Each Column In DataTable.Columns
ColumnStyle = TableStyle.GridColumnStyles(Column.ColumnName)
If Not ColumnStyle Is Nothing Then
'Set width to header text width.
Width = Graphics.MeasureString(ColumnStyle.HeaderText, DataGrid.Font, MaxPixelWidth).Width
'Change width, if data width is wider than header text width.
'Check the width of the data in the first X rows.
Dim iRow As Integer
Dim dr As DataRow
For iRow = 0 To NumberOfRowsToScan - 1
dr = DataTable.Rows(iRow)
If Not IsDBNull(dr(Column.ColumnName)) Then
Width = System.Math.Max(Width, Graphics.MeasureString(dr(Column.ColumnName), DataGrid.Font, MaxPixelWidth).Width)
End If
Next
ColumnStyle.Width = Width + 4
End If
Next
Finally
Graphics.Dispose()
End Try
Return TableStyle
End Function

Public Shared Function GetNewDataGridTextBoxColumn(ByVal MappingName As String) As DataGridTextBoxColumn
Dim TextBoxColumn As DataGridTextBoxColumn = New DataGridTextBoxColumn()
With TextBoxColumn
.MappingName = MappingName
.HeaderText = MappingName
.ReadOnly = True
.Width = 200
End With
Return TextBoxColumn
End Function

Public Shared Function GetNewDataGridTextBoxColumn(ByVal MappingName As String, ByVal [ReadOnly] As Boolean) As DataGridTextBoxColumn
Dim TextBoxColumn As DataGridTextBoxColumn
TextBoxColumn = GetNewDataGridTextBoxColumn(MappingName)
TextBoxColumn.ReadOnly = [ReadOnly]
Return TextBoxColumn
End Function

End Class