Some Cool Tips for .NET(.net技巧集)

Introduction
These are some tips for commonly faced problems in .NET . Some of these tips are mine and some of these i have got from different sources. My aim is not to claim the ownership of these tips,but as a newcomer I had faced these problems and had to do lot of googling. So just to help my fellow programmers I am putting this together. One more reason is Codeproject.com ranks quiet ahead as compared to other sites of same nature, but still I was not able to find some basic solutions as below. So it is small effort from my side.
Windows Application
.NET Framework
VS.NET IDE
Controls
Forms
Buttons
Combo Box
Text Box
DateTime Picker
Data Grid
Panel
ADO.NET
Crystal Reports
Deployment
Miscellaneous
Windows Application
.NET Framework
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 .
Use System.Windows.Forms.SystemInformation .
SystemInformation provides static (Shared in Visual Basic) methods and properties that can be used to get information 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.


There is direct method in .NET for computing the file size but there is no such method for computing directory size and logical drive size.One may think of just adding file size to get directory size and then drive size. But this method has some drawbacks. But we can use Win32 API function GetDiskFreeSpaceEx for this purpose.
The
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:" );
VS.NET IDE
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.
Controls
Forms
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.

This can be achieved very easily though it seems complicated in beginning. Use
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.
Syntax:
MailTo:email@address1.com
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
 &cc=id@internet.node;
 Add entry in the "Blind Copy To" or "BCC" field
 &bcc=id@internet.node
 Add entry in the "Body" field
 &body=Your message here

Following is the complete syntax:
Web Applications:
A href= "mailto:email@address1.com,email@address2.com?cc=email@address3.com&Subject=Hello&body=Happy New
 
Year"
Windows Application:
Use System.Diagnostics.Process
Process process = new Process();
process.StartInfo.FileName = "mailto:email@address1.com,email@address2.com?subject=Hello&cc=email@address3.com
&bcc=email@address4.com&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.
We can position the form initially using following method:
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 form
Now 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();        
 }
Buttons
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
You can trigger a button (Web and Win) by calling
Buttonclick with null parameters
btnClear_Click(null,null)
Alternative: The tip below is provided by Paul Brower 
You can use it this way, if you're planning on doing something with the sender object, you have a reference to it.
button1_click(button1,EventArgs.Empty)
Combo Box
comboBox1.Items.AddRange (FontFamily.Families);
Text Box
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.
Numeric TextBox
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
 {
    if ( !( char.IsDigit( e.KeyChar ) || char.IsControl( e.KeyChar ) ) )
     {                             
       e.Handled = true;                    
     }
}
Numeric TextBox with Decimals
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;                    
     }
}
TextBox Allowing Characters Only
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
 {
    if ( !( char.IsLetter( e.KeyChar ) || char.IsControl( e.KeyChar ) ) )                       
     {                             
       e.Handled = true;                    
     }
}
TextBox Allowing Upper Case Characters Only
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
 {
    if ( !( char.IsUpper( e.KeyChar ) || char.IsControl( e.KeyChar )) )
     {                             
       e.Handled = true;                    
     }
}
TextBox Allowing Lower Case Characters Only
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
 {
    if ( !( char.IsLower( e.KeyChar ) || char.IsControl( e.KeyChar )) )
     {                             
       e.Handled = true;                    
    }
}
Check For Unfilled TextBox
// 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;
}
DateTime Picker
Use following code in some Button Click event:
dateTimePicker1.CustomFormat= " " ;
dateTimePicker1.Format=DateTimePickerFormat.Custom;
Data Grid
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


Hi friends, you may be knowing better ways of doing it, but I managed to find this solution in the time limit I had been given. 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.
/* 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;
Panel
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.
ADO.NET
This is very common problem, as a newcomer I had spent great deal of time to solve this. Suppose you have two controls viz, Combobox and Listbox on same form and Datasource property of both these controls is same. Then the selection in one control selects same item in other control. This problem occurs because of 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" ;
Crystal Reports
The following block makes the status bar of Crystal Report invisible.
foreach(object obj in this.crystalReportViewer1.Controls)
{                                          
 if( obj.GetType()== typeof(System.Windows.Forms.StatusBar))
         {                                          
          StatusBar sBar=(StatusBar)obj;
          sBar.Visible=false;
         }                                          
}
Following block of code generates PDF version of Crystal Report programmatically.
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 ();
You can accomlish this using PrintDialog control and get the computer name using 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);                      
}
Deployment
Miscellaneous
Usually the underline appears only after you press the Alt Key, but you can enable it by changing the Operating System Settings. On Windows XP, Right Click Desktop to bring up the Display Properties Dialog and then choose Appearance tab and then the Effects Button and uncheck the checkbox "Hide Underlined letters for keyboard navigation until I press the ALT Key" .
Though this in not related to .NET directly but it is useful while working with ADO.NET
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.
About Mukund Pujari
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值