本文转自http://www.codeproject.com/KB/miscctrl/tips.aspx
Use the GetFolderPath
method of the System.Environment
class to retrieve this information.
MessageBox.Show( Environment.GetFolderPath( Environment.SpecialFolder.Personal ) );
The Application class has a static member ExecutablePath
that has this information.
string appPath = Application.ExecutablePath;
Alternative: The tip below is provided by cbono2000
System.Reflection.Assembly.GetExecutingAssembly().Location
Use System.Environment's OSVersion
static (shared) property.
OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());
MessageBox.Show(os.Platform.ToString());
Use System.IO.Path.GetFileName
and System.IO.Path.GetFileNameWithoutExtension
static methods.
Use System.IO.Path.GetExtension
static method.
Hi friends, click here to find the best comparison ever between VB.NET and C#.NET .
System.Windows.Forms.SystemInformation
.
SystemInformation
provides static (Shared in Visual Basic) methods and properties that can be used to get in
formation such as Windows display element sizes, operating system settings, network availability, and the capabilities of hardware installed on the system.This class cannot be instantiated. e.g
MousePresent: SystemInformation.MousePresent.ToString() MouseButtonsSwapped: SystemInformation.MouseButtonsSwapped.ToString()
That marks the thread as being Single Thread Apartment which means any multiple threaded calls need to be marshaled over to that thread before they are called. That's there because Windows Forms uses some OLE calls (Clipboard for example), which must be made from the thread that initialized OLE.
Importing CSV files using .NET application
GetDiskFreeSpaceEx
function retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. You can do it as following: Enlist the drives: string[] tempString = Directory.GetLogicalDrives(); foreach(string tempDrive in tempString) { cmbDrives.Items.Add(tempDrive); } cmbDrives.SelectedIndex=0; public sealed class DriveInfo { [DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA")] private static extern long GetDiskFreeSpaceEx(string lpDirectoryName, out long lpFreeBytesAvailableToCaller, out long lpTotalNumberOfBytes, out long lpTotalNumberOfFreeBytes); public static long GetInfo(string drive, out long available, out long total, out long free) { return GetDiskFreeSpaceEx(drive,out available,out total,out free); } public static DriveInfoSystem GetInfo(string drive) { long result, available, total, free; result = GetDiskFreeSpaceEx(drive, out available, out total, out free); return new DriveInfoSystem(drive,result,available,total,free); } } public struct DriveInfoSystem { public readonly string Drive; public readonly long Result; public readonly long Available; public readonly long Total; public readonly long Free; public DriveInfoSystem(string drive, long result, long available, long total, long free) { this.Drive = drive; this.Result = result; this.Available = available; this.Total = total; this.Free = free; } }and then you can use it as
DriveInfoSystem info = DriveInfo.GetInfo("c:");
The IndexOf
method of the string class is case-sensitive. There are two possible ways to overcome this problem.
1. Convert the case of whole sentence and the substring into any one case and then find the index of particular substring.
string strParent = "The Codeproject site is very informative."; string strChild = "codeproject"; // The line below will return -1 when expected is 4. int i = strParent.IndexOf(strChild); // The line below will return proper index int j = strParent.ToLower().IndexOf(strChild.ToLower());
2. Use IndexOf
method of CompareInfo
class in System.Globalization
namespace. This is a more professional and elegant way of doing this.
using System.Globalization; string strParent = "The Codeproject site is very informative."; string strChild = "codeproject"; // We create a object of CompareInfo class for a neutral culture or a culture insensitive object CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; int i = Compare.IndexOf(strParent,strChild,CompareOptions.IgnoreCase);
System.Drawing.Printing.PaperSource
class gives us information about available trays on selected printer. A public property Kind
gives us a value of type PaperSourceKind
which is a enumeration that gives us unique numbers for different kind of trays. But there is a limitation with this property that when tray type is custom it gives a same value i.e, 257. But when you debug you may find a internal property RawKind
which gives unique numbers to even custom tray types. And we need these values actually to send print to correct trays. This is a bug in .NET 1.1 but in .NET 2.0 this has been corrected and RawKind
propety is made pulic. Still there is workaround for this problem in 1.1 and you can access a private field kind
, which actually sets value to Rawkind
property, using Reflection to get proper tray codes.Following is the code snippet to be used.
private int GetRawKind(PaperSource psource) { Type t = psource.GetType(); FieldInfo fi = t.GetField("kind", BindingFlags.NonPublic | BindingFlags.Instance); return (int)fi.GetValue(psource); }
We know that a constructor is a special method that has the same name as the class and returns no value.
It is used to initialize the data in the object we're creating.
There's another kind of constructor�the copy constructor. When we copy one object to another, C# will copy the reference to the first object to the new object, which means that we now have two references to the same object. To make an actual copy, we can use a copy constructor, which is just a standard constructor that takes an object of the current class as its single parameter. For example, here's what a copy constructor for the Student class might look like. Note that we're copying the name field to the new object.
public Student(Student student) { this.name = student.name; }
class Student { private string name; public Student(string name) { this.name = name; } public Student(Student student) { this.name = student.name; } public string Name { get { return name; } set { name = value; } } }
class Final { static void Main() { Student student = new Student ("A"); Student NewStudent = new Student (student); student.Name = "B"; System.Console.WriteLine("The new student's name is {0}", NewStudent.Name); } } The new student's name is A.
There are situations where we would like to decide the value of a constant member at run-time. We may also like to have different constant values for different objects of class. To overcome these shortcomings, C# provides another modifier known as readonly to be used with data members. This modifier is designed to set the value of the member using a constructor method, but cannot be modified later. The readonly members may be declared as either static fields or instance fields. When they are declared as instance fields, they can take different values with different objects. Consider the code below:
class Numbers { public readonly int m; public static readonly int n; public Numbers (int x) { m=x; } static Numbers () { n=100; } }
The value for m
is provided at the time of creation of an object using the constructor with parameter x
. This value will remain constant for that object. Remember, the variable n
is assigned a value of 100
,even before the creation of any objects of Numbers.
In VS.NET Editor in Code View you can select and drag code to a Tab (other than the Clipboard ring) in the ToolBox and then you can drag the code from the Tab to the desired location.
In the VS.NET IDE , from Menu select TOOLS > OPTIONS>TEXT EDITOR (in left window) >ALL LANGUAGES > LINE NUMBERS
You can show Line Numbers depending on languages by selecting specific language in TEXT EDITOR like C# or Basic and checking Line Numbers option
In the VS.NET IDE , from Menu select TOOLS > OPTIONS > ENVIRONMENT (in left window) > FONTS AND COLORS > DISPLAY ITEMS (on right side) >COLLAPSIBLE TEXT
. After selecting this you can set the color.
Set the form's Text and ControlBox properties.
form1.Text = string. Empty; form1.ControlBox = false;
You need to install XP on your machine and the theme should be set to XP.You also need to ensure that the FlatStyle
property of the control is changed to System
and then add following line of code in your Main()
method
static void Main() { Application.EnableVisualStyles(); Application.DoEvents(); Application. Run(new Form1()); }
Set the form's ShowInTaskbar
property to False
to prevent it from being displayed in the Windows taskbar.
MailTo
command for this .I had faced this problem while developing Windows Application. This is very common command and known to many web developers but the great thing about this command is that it works as smoothly with windows application as it works with Web Application.
Some other features of this commands are discussed below:
Features | Syntax |
Address message to multiple recipients | , (comma separating e-mail addresses) |
Add entry in the "Subject" field | ?subject=Subject Field Text |
Add entry in the "Copy To" or "CC" field | &[email protected]; |
Add entry in the "Blind Copy To" or "BCC" field | &[email protected] |
Add entry in the "Body" field | &body=Your message here |
A href="mailto:[email protected],[email protected][email protected]&Subject=Hello&body=Happy New Year"
System.Diagnostics.Process
Process process = new Process(); process.StartInfo.FileName = "mailto:[email protected],[email protected]?subject=Hello&[email protected] &[email protected]&body=Happy New Year" ; process.Start();
I always thought about the ways to create alert windows like messenger pop-ups.This is one such attempt. The logic is simple. Just open the form below taskbar and slowly bring it up using timer so we can have the animated effect. Similarly you can close it. One thing we should be careful about is the 'Resolution' of monitor, since the location of form will change accordingly. So instead of directly locating the form with pre-defined co-ordinates, we will calculate the working area of the screen and place our form accordingly. To calculate the working area of the screen we can use Screen. GetWorkingArea(control)
, which gives the working area of the screen without taskbar.
X=Screen.GetWorkingArea(this).Width; // This line gives the width of working area Y=Screen.GetWorkingArea(this).Height; // This line gives the width of working area this.Location=new Point(X-this.Width,Y+this.Height); // This line sets the initial location of the formNow we will open the form as below:
int i = this.Location.Y; if(i>Y-this.Height) { this.Location=new Point(X-this.Width,i-8); } else { timer1.Stop(); timer1.Enabled=false; timer3.Start(); timer3.Enabled=true; }Similarly we'll close the form
timer3.Stop(); timer3.Enabled=false; int i = this.Location.Y; if(i<Y) { this.Location=new Point(X-this.Width,i+8); } else { timer2.Stop(); timer2.Enabled=false; this.Close(); }
Though both Anchoring and Docking are helpful while resizing application windows, Anchoring helps control in retaining its size and location with respect to container controls when the container is not attached to particulae edge of the container but somewhere in middle.
The Docking feature attaches a control to the edge of its container. When a control is docked to an edge of it's container, it will always stick to that edge. The control will also resize itself to fully fit the edge of the container and also resizes as the container is resized. The Dock property of the Form control can be set to any one of the six values, Top, Bottom, Left, Right, Fill, and None.
In simple words, there cannot be gap between edge of child control and edge of container control when docked.
Anchoring specifies how a control anchors to the edges of its container. When a control is anchored to an edge of its container, the distance between the control and the specified edge remains constant when the container resizes. For example, if a control is anchored to the right edge of its container, the distance between the right edge of the control and the right edge of the container remains constant when the container resizes. A control can be anchored to any combination control edges. If the control is anchored to opposite edges of its container (for example, to the top and bottom), it resizes when the container resizes.
In simple words, there can be or cannot be gap between edge of child control and edge of container control when anchored.
Default
Button of a form means that button on form whose click event fires when Enter
key is pressed. To make a button on form as default set the form's AcceptButton
property. You can do this either through the designer, or through code such as
form1.AcceptButton = button1;
Cancel
Button of a form means that button on form whose click event fires when ESC
key is pressed. To make a button on form as Cancel set the form's CancelButton
property. You can do this either through the designer, or through code such as
form1.CancelButton = button1;
In VB 6.0 it was possible to call CommandButton click event from anywhere like any other method or function (Sub). But in .NET it is not possible in same way. But .NET provides a very simple way to do this. Just use the button's public method PerformClick
.
button1.PerformClick();
Alternative: The tip below is provided by
kaminm
Buttonclick
with null parameters
btnClear_Click(null,null)Alternative: The tip below is provided by Paul Brower
button1_click(button1,EventArgs.Empty)
comboBox1.Items.AddRange (FontFamily.Families);
To prevent the default context menu of a TextBox from showing up, assign a empty context menu as shown below:
textBox1.ContextMenu = new ContextMenu ();
Sometimes it is needed to show data on different lines. The first idea that comes is to set MULTILINE
Property to true and use '\n'
escape sequence for this. But this escape sequence is not supported in .NET textbox. Still it very easy to overcome this problem. To assign multiline text at design time, in the designer window use the LINES
property of TextBox control. For achieving this at runtime, create an array of string and assign it to LINES
property of Textbox as shown below.
string [] strAddress = {"Mukund Pujari","Global Transformation Technologies","Pune, India"}; textBox1.MultiLine=true; textBox1.Lines=strAddress;Alternative: The tip below is provided by joelycat
.NET text boxes don't recognize \n but they do recognize \r\n. Try: textBox1.Text="Line 1\r\nLine2\r\nLine3.";Alternative: The tip below is provided by Robert Rohde
Actually "System.Environment.NewLine" should be used instead. This way you are platform independant.Alternative: The tip below is provided by Redgum
simply use a "RichTextBox" for those areas on your form that require multiple lines of randomly output text, and use a simple text box for those that do not.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsDigit( e.KeyChar ) || char.IsControl( e.KeyChar ) ) ) { e.Handled = true; } }
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsDigit( e.KeyChar) || char.IsControl( e.KeyChar ) ||(e.KeyChar== (char )46)) ) { e.Handled = true; } }
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsLetter( e.KeyChar ) || char.IsControl( e.KeyChar ) ) ) { e.Handled = true; } }
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsUpper( e.KeyChar ) || char.IsControl( e.KeyChar )) ) { e.Handled = true; } }
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsLower( e.KeyChar ) || char.IsControl( e.KeyChar )) ) { e.Handled = true; } }
// Call this function and pass the Textbox as parameter to this function public static bool ChkEmpty(params System.Windows.Forms.TextBox[ ] tb) { int i; for (i = 0; i < tb.Length; i++) { if (tb[i].Text.Trim() == "") { MessageBox.Show("Don't keep field empty"); tb[i].Focus(); return false; } } return true; }
string DecimalSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator; private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if ( !( char.IsDigit( e.KeyChar) || char.IsControl( e.KeyChar ) || (DecimalSeparator.IndexOf(e.KeyChar) != -1 ) ) ) { e.Handled = true; } }
Whenever a textbox having text gets focus, the text in it is selected. To avoid this just set the SelectionStart
property of this textbox to length of the text in it, mostly in ENTER
. event of the textbox.If anyone has better idea please suggest.
textBox1.SelectionStart = textBox1.Text.Length;
Use following code in some Button Click event:
dateTimePicker1.CustomFormat=" "; dateTimePicker1.Format=DateTimePickerFormat.Custom;
The checkbox in checkbox column of datagrid shows indeterminate status by default. To remove this behaviour set AllowNull
property of the CheckBox column to false
as below:
DataGridTableStyle ts1 = new DataGridTableStyle(); // Create New TableStyle ts1.MappingName = "Items"; // Assign the name of Data Table to which Style is applied DataGridColumnStyle boolCol = new DataGridBoolColumn(); // Create a CheckBox column boolCol.MappingName = "ch"; // Assign the name of Data Column boolCol.AllowNull=false; // This property actually removes the indeterminate status of checkboxes
/* The logic is that, while looping through datatable we save the values of current column and previous column and we compare it. If Current Value is same as Previous Value, we don't show it in grid and if it is not same then we show it. 1. We save value of current column in variable 'strCurrentValue'. 2. After the loop we assign the value in 'strCurrentValue' to variable 'strPreviousValue'. 3. And in next loop, we get new value in 'strCurrentValue'. 4. Now we can compare value in 'strCurrentValue' and 'strPreviousValue' and accordingly show or hide values in the column. */ int m; for(m=0;m<8;m++) { object cellValue = dt.Rows[m]["Category"]; // Here we catch the value form current column strCurrentValue=cellValue.ToString().Trim(); // We assign the above value to 'strCurrentValue' if(strCurrentValue!=strPreviousValue) // Now compare the current value with previous value { dt.Rows[m]["Category"]=strCurrentValue; // If current value is not equal to previous // value the column will display current value } else { dt.Rows[m]["Category"]=string.Empty; // If current value is equal to previous value // the column will be empty } strPreviousValue=strCurrentValue; // assign current value to previous value } strCurrentValue=string.Empty; // Reset Current and Previous Value strPreviousValue=string.Empty;
You can make a panel or label transparent by specifying the alpha value
for the Background color
.
panel1.BackColor = Color.FromArgb(65, 204, 212, 230); NOTE:In the designer you have to enter these values manually in the edit box. Don't select the color using the ColorPicker.
Though there is no direct Print
method for printing the contents of web browser but there is very easy way which does more than printing. Use ExecWB
method of Web Browser control. This method executes a command on an OLE object and returns the status of the command execution using the IOleCommandTarget
interface. By using this method you can print, preview ,set up the page and do many more things. You can also decide whether the dialogs should be prompted to user or not.
For details of syntax and values of attributes please refer MSDN
.
In the example given below, we are printing the contents by specifying it in first parameter and we are prompting the Printer Selection Dialog to user by passing second parameter
object em =null;
axWebBrowser1.ExecWB (SHDocVw.OLECMDID.OLECMDID_PRINT,SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER,
ref em, ref em);
Similarly you can use this for setting Page Set Up. E.g.
object em =null;
axWebBrowser1.ExecWB (SHDocVw.OLECMDID.OLECMDID_PAGESETUP,SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER,
ref em, ref em);
The following steps outline how Microsoft Internet Explorer accesses the printer settings:
1. Internet Explorer tries to obtain the values from the following registry key: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\PageSetup
2. If the key in step 1 does not exist, Internet Explorer tries to create this key by copying the values from the following key: HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\PageSetup
3. If the key in step 2 does not exist, default values are provided. <NOTE: These registry values are system-wide and affect all instances of the WebBrowser control and Internet Explorer for the current user. Following e.g. shows how to set custom header for IE or WebBrowser control.
public void SetupHeaderWB() { string strPath = "Software\\Microsoft\\Internet Explorer\\PageSetup"; Microsoft.Win32.RegistryKey oKey = null; /* The following lines of code takes care that error does not occur if registry settings are not at proper path.*/ oKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey (strPath, true); if (oKey! =null) { oKey = microsoft.Win32.Registry.CurrentUser.OpenSubKey (strPath, true); } else { oKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (strPath, true); } string strKey = "header"; object oValue = "Test header"; oKey.SetValue (strKey, oValue); /* You can also get the value in registry by following line of code string strValue=oKey.GetValue (strKey).ToString();*/ oKey.Close(); }
BindingContext
property of controls. By default the BindingContext member of each of the two controls is set to the
Form's BindingContext. Thus, the default behavior is for the ComboBox and Listbox to share the same BindingContext, and that's why the selection in the ComboBox is synchronized with the current item of Listbox. If you do not want this behavior, create a new BindingContext member for at least one of the controls.
comboBox1.DataSource = dataset.Tables[ "Items" ]; comboBox1.ValueMember = "CustomerID"; comboBox1.DisplayMember = "CustomerID"; listBox1.BindingContext = new BindingContext(); // Set the BindingContext property of ListBox to new BindingContext listBox1.DataSource = dataset.Tables[ "Items" ]; listBox1.ValueMember = "CustomerID"; listBox1.DisplayMember = "CustomerID";
foreach(object obj in this.crystalReportViewer1.Controls) { if( obj.GetType()== typeof(System.Windows.Forms.StatusBar)) { StatusBar sBar=(StatusBar)obj; sBar.Visible=false; } }
ReportDocument O_Report=new ReportDocument(); ExportOptions exportOpts = new ExportOptions(); PdfRtfWordFormatOptions pdfFormatOpts = new PdfRtfWordFormatOptions (); DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions(); exportOpts = O_Report.ExportOptions; // Set the PDF format options. exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat; exportOpts.FormatOptions = pdfFormatOpts; // Set the disk file options and export. exportOpts.ExportDestinationType = ExportDestinationType.DiskFile; diskOpts.DiskFileName = "C://Trial.pdf"; // This is the path where the file will be saved exportOpts.DestinationOptions = diskOpts; O_Report.Export ();
printDialog1.PrinterSettings.PrinterName
// Create a Report Document ReportDocument O_Report=new ReportDocument(); private void btnPrint_Click(object sender, System.EventArgs e) { try { // Create a Print Dialog PrintDialog printDialog1 = new PrintDialog(); // Create a Print Document PrintDocument pd = new PrintDocument(); printDialog1.Document=pd; printDialog1.ShowNetwork=true; printDialog1.AllowSomePages=true; DialogResult result = printDialog1.ShowDialog(); if (result == DialogResult.OK) { PrintReport(printDialog1.PrinterSettings.PrinterName); } } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void PrintReport(string printerName) { // Select the printer. O_Report.PrintOptions.PrinterName = printerName; /* Print the report. Set the startPageN and endPageN parameters to 0 to print all pages.*/ O_Report.PrintToPrinter(1, false,0,0); }
Windows2.CreateToolWindow2()
is a method used to host user control in VS 2005 toolwindow via Add-in.
Window CreateToolWindow2 ( AddIn Addin, string Assembly, string Class, string Caption, string GuidPosition, [InAttribute] out Object ControlObject )The last parameter
ControlObject
of this method returns a reference to hosted user control. There are two ways to get a reference to hosted user control.
System.Runtime.InteropServices
namespace MyControl { [ComVisibleAttribute(true)] public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } } }
"Hide Underlined letters for keyboard navigation until I press the ALT Key"
.
1) Open a New notepad and save it with "udl" extension, suppose "New.udl". 2) Now you will see that it's icon is changed. 3) Open it, you will find Data Link properties dialog box. 4) For SQl Server connection string select <CODE>Microsoft OLE DB Provider For SQL Server in Provider Tab. 5) Click button "Next" or select Connection Tab 6) Here you can select all connection details and press button Test Connection. If it is successful close this dialog box. 7) Now open this file using "Notepad", you will find the connection string. Though it is built for OLE DB type of connection, you can use for SQL Server connection by removing Provider attribute. NOTE: If you are using SQL Authentication with password, then check the checkbox Allow Saving Password. This is necessary so that password appears in connection string.