当前位置: 代码迷 >> 综合 >> Some Cool Tips for .NET(.net技巧集)
  详细解决方案

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

热度:37   发布时间:2023-12-13 07:50:40.0
原文地址:http://www.codeproject.com/useritems/tips.asp#xx1371061xx
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
1. How to get the path for "My Documents" and other system folders?
2. How to get the path to my running EXE? 
3. How to determine which operating system is running?
4. How to get a file's name from the complete path string?
5. How to get a file's extension from the complete path string?
6. What is difference beween VB.NET and C#.NET?
7. How to find whether your system has mouse or the number of buttons, whether it has wheel, or whether the mouse buttons are swapped or size of your monitor and many such information?
8. What is the purpose of the [STA Thread] attribute for the Main method of a C# program?
9. How to import CSV data using .NET application?
10. How to find size of logical drives using .NET?
VS.NET IDE
1. How to manage code snippets in VS.NET IDE?
2. How to display Line Numbers in code editor? 
3. How to change the color of the regions?
Controls
Forms
1. How to create a form with resizing borders and no title bar?
2. How to use XP Themes with Windows Forms using the .NET?
3. How to prevent a form from being shown in the taskbar?
4. How to open default E-mail client on your system with all parameters entered in it,like Outlook Express or Eudora, from your .NET windows or Web Application?
5. How to create Pop-Up Alert windows like messengers?
Buttons
1. How to set the default button for a form?
2. How to set the Cancel button for a form?
3. How to trigger a button click event? 
Combo Box
1. How to fill a ComboBox with the available fonts?
Text Box
1. How to disable the default ContextMenu of a TextBox?
2. How to enter multiline text in textbox through code?
3. Some useful TextBox Validations  
DateTime Picker
1. How to make the DateTimePicker show empty text if no date is selected?
Data Grid
1. How to remove the indeterminate status of checkbox in datagrid?
2. How to group columns in DataGrid?
Panel
1. How to make a Panel or Label semi-transparent on a Windows Form?
ADO.NET
1. How to bind two controls to the same DataTable without having changes in one control also change the other control?
Crystal Reports
1. How to hide the status bar of Crystal Report in Report Viewer?
2. How to generate PDF version of Crystal Report programmatically?
3. How to select a printer while printing through Crystal Report programmatically?
Deployment
1. How to install database while deploying .NET application ?
2. How to install MSDE while deploying .NET application?
3. How to create conditional shortcuts while deploying .NET application?
Miscellaneous
1. How to enable the mnemonics (underline) being displayed when an application is launched
2. An easy way to build connection string.
Windows Application
.NET Framework
#1. How to get the path for "My Documents" and other system folders?
Use the GetFolderPath method of the System.Environment class to retrieve this information.
 MessageBox.Show( Environment.GetFolderPath( Environment.SpecialFolder.Personal ) );
#2. How to get the path to my running EXE?
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
#3. How to determine which operating system is running?
Use System.Environment's OSVersion static (shared) property.
OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());
MessageBox.Show(os.Platform.ToString());
#4. How to get a file's name from the complete path string?
Use System.IO.Path.GetFileName and System.IO.Path.GetFileNameWithoutExtension static methods.
#5. How to get a file's extension from the complete path string?
Use System.IO.Path.GetExtension static method.
#6. What is difference beween VB.NET and C#.NET?
Hi friends, click here to find the best comparison ever between VB.NET and C#.NET .
#7. How to find whether your system has mouse or the number of buttons, whether it has wheel, or whether the mouse buttons are swapped or size of your monitor and many such information?
  • Download source files - 8.65 Kb
  • Download demo project - 4.60 Kb
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()
#8. What is the purpose of the [STA Thread] attribute for the Main method of a C# program?
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.
#9. How to import CSV data using .NET application?
Importing CSV files using .NET application
#10. How to find size of logical drives using .NET?
  • Download source files - 10.0 Kb
  • Download demo project - 5.48 Kb


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
#1. How to manage code snippets in 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.
#2. How to display Line Numbers in code editor? 
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
#3. How to change the color of the regions? 
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
#1. How to create a form with resizing borders and no title bar?
Set the form's Text and ControlBox properties.
 
form1.Text = string. Empty;
form1.ControlBox = false;
#2. How to use XP Themes with Windows Forms using the .NET?
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());
}
#3. How to prevent a form from being shown in the taskbar?
Set the form's ShowInTaskbar property to False to prevent it from being displayed in the Windows taskbar.
#4. How to open default E-mail client on your system with all parameters entered in it,like Outlook Express or Eudora, from your .NET windows or Web Application?

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();
#5. How to create Pop-Up Alert windows like messengers?
  • Download source files - 27.2 Kb
  • Download demo project - 13.7 Kb

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
#1. How to set the default button for a form?
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;
#2. How to set the Cancel button for a form?
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;
#3. How to trigger a button click event?
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
#1. How to fill a ComboBox with the available fonts?
comboBox1.Items.AddRange (FontFamily.Families);
Text Box
#1. How to disable the default ContextMenu of a TextBox?
To prevent the default context menu of a TextBox from showing up, assign a empty context menu as shown below:
textBox1.ContextMenu = new ContextMenu ();
#2. How to enter multiline text in textbox through code?
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.
#3. Some useful TextBox Validations 
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
#1. How to make the DateTimePicker show empty text if no date is selected?
Use following code in some Button Click event:
dateTimePicker1.CustomFormat= " " ;
dateTimePicker1.Format=DateTimePickerFormat.Custom;
Data Grid
#1. How to remove the indeterminate status of checkbox in datagrid?
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
#2. How to group columns in DataGrid?
  • Download source files - 9.57 Kb
  • Download demo project - 5.26 Kb


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
#1. How to make a Panel or Label semi-transparent on a Windows Form?
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
#1. How to bind two controls to the same DataTable without having changes in one control also change the other control?
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
#1. How to hide the status bar of Crystal Report in Report Viewer?
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;
         }                                          
}
#2. How to generate PDF version of Crystal Report programmatically?
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 ();
#3. How to select a printer while printing through Crystal Report programmatically?
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
#1. How to install database while deploying .NET application ?
Solution 1
Solution 2
#2. How to install MSDE while deploying .NET application?
Installing MSDE with .NET Application
#3. How to create conditional shortcuts while deploying .NET application?
Creating Conditional shortcuts
Miscellaneous
#1. How to enable the mnemonics (underline) being displayed when an application is launched
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" .
#2. An easy way to build connection string.
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