Show Line Numbers in Visual Studio
It is always better to have Line numbers displayed in Visual Studio when you debug your VB or C# Project. It is not turned on by default. you can turn it on as shown below
Monday, November 8, 2010
Saturday, September 18, 2010
Cint Function in VB.NET / Convert String to Integer in VB.NET
Abstract Classes in VB.NET
Abstract classes are base classes that has to be inherited. A class can be made as an abstract with MustInherit modifier
Abstract classes can contain abstract methods also. Abstract methods are the ones where only signature is available in the base class and their implementation is taken care in derived classes.
Following is an example of abstract class:
the class contains one Abstract method
The class can be inherited as shown below:
The class can be used as shown below:
the first call uses the method from the base class and the second one uses the Method we had overriden in the derived class
Abstract classes can contain abstract methods also. Abstract methods are the ones where only signature is available in the base class and their implementation is taken care in derived classes.
Following is an example of abstract class:
Public MustInherit Class ClassAbs Public Sub ExampleMethod() MessageBox.Show("This is sample") End Sub Public MustOverride Sub ExampleMethod_ShouldBeInherited() Public Overridable Sub ExampleMethod_CanBeCalledFromBase() MessageBox.Show("This is sample") End Sub End Class
the class contains one Abstract method
The class can be inherited as shown below:
Public Class ClassDerivedFromAbstract Inherits ClassAbs Public Sub ExampleAbstract() MyBase.ExampleMethod_CanBeCalledFromBase() End Sub Public Overrides Sub ExampleMethod_ShouldBeInherited() End Sub Public Overrides Sub ExampleMethod_CanBeCalledFromBase() MessageBox.Show("This is sample from Derived") End Sub End Class
The class can be used as shown below:
Dim CAb As New ClassDerivedFromAbstract CAb.ExampleMethod_CanBeCalledFromBase() CAb.ExampleMethod_ShouldBeInherited()
the first call uses the method from the base class and the second one uses the Method we had overriden in the derived class
Thursday, September 16, 2010
How to make Windows Form fit FullScreen using VB.NET
We have already seen How to Get Width and Height of Desktop Screen using C#/VB.NET in previous post. The following VB.NET snippet provides a method to make the Windows Form fir the Desktop screen
You can add this snippet in Form_Load sub
Dim iWidth As Integer = Screen.PrimaryScreen.Bounds.Width Dim iHeight As Integer = Screen.PrimaryScreen.Bounds.Height Me.Width = iWidth Me.Height = iHeight Me.Location = New System.Drawing.Point(0, 0)
You can add this snippet in Form_Load sub
Friday, August 27, 2010
Video Tutorial - Add a new button on Office backstage using C#
How to add a new button to Office (Excel) Backstage from Addin using VSTO (C#)
The following XML adds a new button on Backstage. The button will be added at the end as we didn't specify a location.
The following XML adds a new button on Backstage. The button will be added at the end as we didn't specify a location.
Thursday, August 26, 2010
What is a Backstage view and How to customize it?
Backstage view in Office 2010 - An Introduction
Backstage was introducted in Office 2010 to hold commands and menus which are do some work 'on the document', for example, Printing, Publishing to SharePoint etc.
Backstage view is part of Office Fluent UI and very much customizable. The following video shows the elements of Backstage view.
Office 2010 BackStage View - An Introduction to customizable elements
Tuesday, August 24, 2010
How to Get Width and Height of Desktop Screen using C#/VB.NET
How to resize Windows form to fit Windows screen using C#/VB.NET
The following code resizes the Form Window to fit the entire screen .
The following code resizes the Form Window to fit the entire screen .
int iWindowWidth = Screen.PrimaryScreen.Bounds.Width; int iWindowHeight = Screen.PrimaryScreen.Bounds.Height; this.Size = new Size(iWindowWidth, iWindowHeight ) ;
Saturday, August 7, 2010
How to Enable a Disabled VSTO Addin
VSTO Addin is not getting Executed / VSTO Addin Stopped working
If your VSTO addin stopped working suddenly, it might because the Application would have taken precautionary measure by disabling your Addin.
The disabled addins can be checked from Excel/Word options from Backstage View as shown below:
Select the Addin you want to enable and select Enable:
If your VSTO addin stopped working suddenly, it might because the Application would have taken precautionary measure by disabling your Addin.
The disabled addins can be checked from Excel/Word options from Backstage View as shown below:
Select the Addin you want to enable and select Enable:
Tuesday, August 3, 2010
How to Add Images to Project Resources in C#/.NET
How to add/deploy Images in C#/.NET (Visual Studio)
You can add images as resources to the project. The images will be stored as part of your solution and get deployed when you deploy your solution. To add an image to the project, select Resources Tab from Project Properties and click on Add Resources; Select an appropriate file
Resources Tab in Visual Studio
Once the image is added it will be displayed as shown below:
The resource file is part of your project as shown below:
To access the image from code use the following
public System.Drawing.Bitmap GetButtonImage(Office.IRibbonControl control) { switch(control.Id) { case "btnmoscow": return Properties.Resources.moscow; . . , default: return null; } }
Friday, July 30, 2010
C#/VB.NET Excel Autofilter - Specify Multiple Criteria using Array
C#/VB.NET Excel Autofilter - Only Last Value is Displayed
Here is a simple example of Filtering ListObjects using Excel AutoFilter function. This example uses the following spreadsheet
Here is a simple example of Filtering ListObjects using Excel AutoFilter function. This example uses the following spreadsheet
The following C# code will filter 'Apple' and 'Orange' using an Array
private void ExcelFilterExample() { String[] FilterList = {"Apple","Orange"}; Excel.Workbook oWB = Globals.ThisAddIn.Application.Workbooks.Open(@"C:\Users\comp\Documents\FreshFruitsnVegetables.xls"); Excel.Worksheet oWS = oWB.Worksheets[1]; oWS.ListObjects.AddEx (Excel.XlListObjectSourceType.xlSrcRange, oWS.UsedRange, System.Type.Missing ,Excel.XlYesNoGuess.xlYes).Name = "FruitList"; oWS.ListObjects["FruitList"].Range.AutoFilter(2, FilterList, Excel.XlAutoFilterOperator.xlFilterValues ); }
VB.NET Excel Offset Function / C# Excel Offset Function
How to Offset Excel Ranges using VB.NET / C#
The following code gives you a better insight into offsetting a range using C#. The code uses get_Offset method to Offset the range
private void MathTableExample() { Microsoft.Office.Interop.Excel.Range oRng; oRng = Globals.ThisAddIn.Application.get_Range("A1"); for (int i = 1; i <= 10; i++) { // Uses Offset Method of Excel oRng.get_Offset(i, 0).Value2 = "9 x " + i.ToString() + " = " + (i * 9).ToString(); } }
Thursday, July 22, 2010
How to disable/suppress Addin Errors in Excel/ Word
Disable/suppress Addin Errors while loading in Excel/ Word (VSTO/.NET)
If you don't want to show your users the following kind of embarrassing errors:
Use the following option from Excel/Word Options --> Advanced
Disable Errors while Loading
Sunday, July 18, 2010
NOT Operator in C# (.NET)
What is the equivalent for VB NOT operator in C#
VB Programmers use NOT operator often. For example,
or
You can do the same in C# as shown below:
and also in the following context to toggle the Button and TaskPane
VB Programmers use NOT operator often. For example,
If Not Range is nothing
or
FlagDone = Not Failed
You can do the same in C# as shown below:
Microsoft.Office.Interop.Excel.Range oRng; oRng = null; if (object.ReferenceEquals(oRng,null)) { oRng = null; }
and also in the following context to toggle the Button and TaskPane
Globals.Ribbons.RibbonFB.button1.Enabled =(!CusPane.Visible);
Monday, July 5, 2010
How to make .NET application compatible to all platforms 32 bit and 64 bit
How to convert a 32 bit .NET application to 64 bit
If you have developed application for 32 bit and want to make the application work in all platforms, change the Platform target to all from Project properties
If you have developed application for 32 bit and want to make the application work in all platforms, change the Platform target to all from Project properties
Platform Compatibility (32 bit, 64 bit) for .NET application
Saturday, June 19, 2010
How to Display WebPage Title on Windows Form using C#/.NET
Change Windows Form Caption dynamically using C#/VB.NET to display WebPage Title
It is good to display Webpage title on the userform or any other control that hosts Webbrowser. This ressembles the functionaliy of Internet Explorer. The following code does the same:
The code uses DocumentCompleted event to update the WinForm's caption.
It is good to display Webpage title on the userform or any other control that hosts Webbrowser. This ressembles the functionaliy of Internet Explorer. The following code does the same:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { this.Text = webBrowser1.Document.Title; }
The code uses DocumentCompleted event to update the WinForm's caption.
Wednesday, June 16, 2010
How to Browse WebPages using WinForm
How to use WebControl in Windows Forms
WebBrowser control can be used to display Webpages on userform. Add a webbrowser control to the userform
Default page can be set used the URL property. Here I have set URL property to bing.com
WebBrowser Control and Userform
The same can be set through code using:
webBrowser1.Navigate("http://www.bing.com");
Friday, June 11, 2010
C# Color Code and RGB Values / VB.NET Color Code and RGB Values
Color Name | RGB Value |
RGB Value of AliceBlue | #F0F8FF |
RGB Value of AntiqueWhite | #FAEBD7 |
RGB Value of Aqua | #00FFFF |
RGB Value of Aquamarine | #7FFFD4 |
RGB Value of Azure | #F0FFFF |
RGB Value of Beige | #F5F5DC |
RGB Value of Bisque | #FFE4C4 |
RGB Value of Black | #000000 |
RGB Value of BlanchedAlmond | #FFEBCD |
RGB Value of Blue | #0000FF |
RGB Value of BlueViolet | #8A2BE2 |
RGB Value of Brown | #A52A2A |
RGB Value of BurlyWood | #DEB887 |
RGB Value of CadetBlue | #5F9EA0 |
RGB Value of Chartreuse | #7FFF00 |
RGB Value of Chocolate | #D2691E |
RGB Value of Coral | #FF7F50 |
RGB Value of CornflowerBlue | #6495ED |
RGB Value of Cornsilk | #FFF8DC |
RGB Value of Crimson | #DC143C |
RGB Value of Cyan | #00FFFF |
RGB Value of DarkBlue | #00008B |
RGB Value of DarkCyan | #008B8B |
RGB Value of DarkGoldenrod | #B8860B |
RGB Value of DarkGray / DarkGrey | #A9A9A9 |
RGB Value of DarkGreen | #006400 |
RGB Value of DarkKhaki | #BDB76B |
RGB Value of DarkMagenta | #8B008B |
RGB Value of DarkOliveGreen | #556B2F |
RGB Value of DarkOrange | #FF8C00 |
RGB Value of DarkOrchid | #9932CC |
RGB Value of DarkRed | #8B0000 |
RGB Value of DarkSalmon | #E9967A |
RGB Value of DarkSeaGreen | #8FBC8F |
RGB Value of DarkSlateBlue | #483D8B |
RGB Value of DarkSlateGray / DarkSlateGrey | #2F4F4F |
RGB Value of DarkTurquoise | #00CED1 |
RGB Value of DarkViolet | #9400D3 |
RGB Value of DeepPink | #FF1493 |
RGB Value of DeepSkyBlue | #00BFFF |
RGB Value of DimGray / DimGrey | #696969 |
RGB Value of DodgerBlue | #1E90FF |
RGB Value of FireBrick | #B22222 |
RGB Value of FloralWhite | #FFFAF0 |
RGB Value of ForestGreen | #228B22 |
RGB Value of Fuchsia | #FF00FF |
RGB Value of Gainsboro | #DCDCDC |
RGB Value of GhostWhite | #F8F8FF |
RGB Value of Gold | #FFD700 |
RGB Value of Goldenrod | #DAA520 |
RGB Value of Gray / Grey | #808080 |
RGB Value of Green | #008000 |
RGB Value of GreenYellow | #ADFF2F |
RGB Value of Honeydew | #F0FFF0 |
RGB Value of HotPink | #FF69B4 |
RGB Value of IndianRed | #CD5C5C |
RGB Value of Indigo | #4B0082 |
RGB Value of Ivory | #FFFFF0 |
RGB Value of Khaki | #F0E68C |
RGB Value of Lavender | #E6E6FA |
RGB Value of LavenderBlush | #FFF0F5 |
RGB Value of LawnGreen | #7CFC00 |
RGB Value of LemonChiffon | #FFFACD |
RGB Value of LightBlue | #ADD8E6 |
RGB Value of LightCoral | #F08080 |
RGB Value of LightCyan | #E0FFFF |
RGB Value of LightGoldenrodYellow | #FAFAD2 |
RGB Value of LightGreen | #90EE90 |
RGB Value of LightGray / LightGrey | #D3D3D3 |
RGB Value of LightPink | #FFB6C1 |
RGB Value of LightSalmon | #FFA07A |
RGB Value of LightSeaGreen | #20B2AA |
RGB Value of LightSkyBlue | #87CEFA |
RGB Value of LightSlateGray / LightSlateGrey | #778899 |
RGB Value of LightSteelBlue | #B0C4DE |
RGB Value of LightYellow | #FFFFE0 |
RGB Value of Lime | #00FF00 |
RGB Value of LimeGreen | #32CD32 |
RGB Value of Linen | #FAF0E6 |
RGB Value of Magenta | #FF00FF |
RGB Value of Maroon | #800000 |
RGB Value of MediumAquamarine | #66CDAA |
RGB Value of MediumBlue | #0000CD |
RGB Value of MediumOrchid | #BA55D3 |
RGB Value of MediumPurple | #9370DB |
RGB Value of MediumSeaGreen | #3CB371 |
RGB Value of MediumSlateBlue | #7B68EE |
RGB Value of MediumSpringGreen | #00FA9A |
RGB Value of MediumTurquoise | #48D1CC |
RGB Value of MediumVioletRed | #C71585 |
RGB Value of MidnightBlue | #191970 |
RGB Value of MintCream | #F5FFFA |
RGB Value of MistyRose | #FFE4E1 |
RGB Value of Moccasin | #FFE4B5 |
RGB Value of NavajoWhite | #FFDEAD |
RGB Value of Navy | #000080 |
RGB Value of OldLace | #FDF5E6 |
RGB Value of Olive | #808000 |
RGB Value of OliveDrab | #6B8E23 |
RGB Value of Orange | #FFA500 |
RGB Value of OrangeRed | #FF4500 |
RGB Value of Orchid | #DA70D6 |
RGB Value of PaleGoldenrod | #EEE8AA |
RGB Value of PaleGreen | #98FB98 |
RGB Value of PaleTurquoise | #AFEEEE |
RGB Value of PaleVioletRed | #DB7093 |
RGB Value of PapayaWhip | #FFEFD5 |
RGB Value of PeachPuff | #FFDAB9 |
RGB Value of Peru | #CD853F |
RGB Value of Pink | #FFC0CB |
RGB Value of Plum | #DDA0DD |
RGB Value of PowderBlue | #B0E0E6 |
RGB Value of Purple | #800080 |
RGB Value of Red | #FF0000 |
RGB Value of RosyBrown | #BC8F8F |
RGB Value of RoyalBlue | #4169E1 |
RGB Value of SaddleBrown | #8B4513 |
RGB Value of Salmon | #FA8072 |
RGB Value of SandyBrown | #F4A460 |
RGB Value of SeaGreen | #2E8B57 |
RGB Value of Seashell | #FFF5EE |
RGB Value of Sienna | #A0522D |
RGB Value of Silver | #C0C0C0 |
RGB Value of SkyBlue | #87CEEB |
RGB Value of SlateBlue | #6A5ACD |
RGB Value of SlateGray / SlateGrey | #708090 |
RGB Value of Snow | #FFFAFA |
RGB Value of SpringGreen | #00FF7F |
RGB Value of SteelBlue | #4682B4 |
RGB Value of Tan | #D2B48C |
RGB Value of Teal | #008080 |
RGB Value of Thistle | #D8BFD8 |
RGB Value of Tomato | #FF6347 |
RGB Value of Turquoise | #40E0D0 |
RGB Value of Violet | #EE82EE |
RGB Value of Wheat | #F5DEB3 |
RGB Value of White | #FFFFFF |
RGB Value of WhiteSmoke | #F5F5F5 |
RGB Value of Yellow | #FFFF00 |
RGB Value of YellowGreen | #9ACD32 |
Event Handler to Handle Multiple Events (C#/.NET)
Event handlers are of great use especially in WinForms programming. There might be a case where you will be having multiple Objects (Buttons for example), which requires to fire events of same type
The following snippet shows how to declare an eventhandler and assign it to multiple events
The above event handler is a generic one. It contains two arguments the sender, which contains the object that fired the event and Arguments.
Statement
b1 = (System.Windows.Forms.Button)sender;
Assigns (or casts) the object to button object. If casting is not done Cannot implicitly convert type 'object' to 'System.Windows.Forms.Button'. An explicit conversion exists (are you missing a cast?) is thrown
The snippet below assigns the sub - btn_Click with click events of both buttons
The following snippet shows how to declare an eventhandler and assign it to multiple events
private void btn_Click(object sender, EventArgs e) { Button b1; b1 = (System.Windows.Forms.Button)sender; MessageBox.Show("Button Clicked := " + b1.Name.ToString()); b1.ForeColor = Color.Red; }
The above event handler is a generic one. It contains two arguments the sender, which contains the object that fired the event and Arguments.
Statement
b1 = (System.Windows.Forms.Button)sender;
Assigns (or casts) the object to button object. If casting is not done Cannot implicitly convert type 'object' to 'System.Windows.Forms.Button'. An explicit conversion exists (are you missing a cast?) is thrown
The snippet below assigns the sub - btn_Click with click events of both buttons
button1.Click += new EventHandler(btn_Click); button2.Click += new EventHandler(btn_Click);
Thursday, June 10, 2010
Could not find type 'WindowsFormsControlLibrary1.UserControl1
What is solution for - "Visual Studio has encountered an exception. This may be caused by an extension."
---------------------------
Microsoft Visual Studio
---------------------------
Visual Studio has encountered an exception. This may be caused by an extension.
You can get more information by running the application together with the /log parameter on the command line, and then examining the file 'C:\Users\comp\AppData\Roaming\Microsoft\VisualStudio\10.0\ActivityLog.xml'.
Microsoft Visual Studio
---------------------------
Visual Studio has encountered an exception. This may be caused by an extension.
You can get more information by running the application together with the /log parameter on the command line, and then examining the file 'C:\Users\comp\AppData\Roaming\Microsoft\VisualStudio\10.0\ActivityLog.xml'.
Wednesday, June 9, 2010
User Controls not showing up in the toolbox / New usercontrol not appearing in toolbox
User Control Will Not Appear In Toolbox / User Control not listed in toolbox
Here is a method to add UserControl manually to the toolbox:
Step 1: Right Click on ToolBox and select Choose Items
Step 2: Choose the ToolBox items you want to display. If your Usercontrol is not listed in Toolbox then Browse for the DLL and enable the checkbox
Here is a method to add UserControl manually to the toolbox:
Step 1: Right Click on ToolBox and select Choose Items
Step 2: Choose the ToolBox items you want to display. If your Usercontrol is not listed in Toolbox then Browse for the DLL and enable the checkbox
Monday, June 7, 2010
How to make ActiveX control to interact with COM Object
How to make ActiveX control to expose COM Object
The Register for COM interop Checkbox indicates that your managed application will expose a COM object (a COM callable wrapper) that allows a COM object to interact with your managed application.
The Output type property in the Application page of the Project Designer for this application must be set to Class Library in order for the Register for COM interop property to be available.
Saturday, May 8, 2010
How to format Currency (Pound/Dollar/Euro etc) using C#/VB.NET/Csharp Writeline function
Formatting Currency in C#/VB.NET/Csharp Writeline function
You can use .NET's Composite Formatting to format the currency as shown below
If you want to convert it into dollars/pounds etc you need to change the culture info :
The above code needs the following directives
You can use .NET's Composite Formatting to format the currency as shown below
Double Incentive = 234.45; Console.WriteLine("The agreed incentive in local currency is {0:C} ", Incentive);
If you want to convert it into dollars/pounds etc you need to change the culture info :
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false); Console.WriteLine("The agreed incentive in USD is {0:C} ", Incentive); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB", false); Console.WriteLine("The agreed incentive in GBP is {0:C} ", Incentive);
The above code needs the following directives
using System.Threading; using System.Globalization;
en-UK is an invalid culture identifier - VB.NET/C#/Csharp
Culture is not supported. Parameter name: name en-UK is an invalid culture identifier.
We are used to en-UK as culture. but for some reasons MS doesn't support en-UK (UK is used for Ukraine)
Hence replace
with
We are used to en-UK as culture. but for some reasons MS doesn't support en-UK (UK is used for Ukraine)
Hence replace
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-UK", false);
with
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB", false);
Friday, May 7, 2010
How to pass an argument by reference in Csharp/C#/VB.NET
Pass by Reference/Pass by Value in VB.NET/C-Sharp/C#
Here is an example of passing an argument to a function by Value:
private static void PassByValueExample(double Salary)// { Salary = Salary * 1.2; }
Here is how it is passed as reference
private static void PassByRefExample(ref double Salary)// { Salary = Salary * 1.2; }
The following code shows the difference between the two
Console.WriteLine("Salary before hike is {0:F}", Sal); PassByValueExample( Sal); Console.WriteLine("Salary after hike is {0:F}", Sal); Console.WriteLine("Salary before hike is {0:F}", Sal); PassByRefExample(ref Sal); Console.WriteLine("Salary after hike is {0:F}", Sal);
See also:
Search Engine Optimization and SEO Tools
webbhotell
Input string was not in a correct format. - Csharp/VB.NET WriteLine Function
If you are using VB.NET/C# Writeline function and facing the following error, it has to do with formatting
Wrong :
Correct:
USe appropriate composite format string - decimal , double
Wrong :
double Sal = 1250.45; Console.WriteLine("Salary before hike is {0:D}", Sal); //Decimal instead of double Console.WriteLine("Salary before hike is {F}", Sal); //Index is missing
Correct:
double Sal = 1250.45; Console.WriteLine("Salary before hike is {0:F}", Sal);
USe appropriate composite format string - decimal , double
Friday, April 23, 2010
How to pass Database Field Name to SQLDataReader GetString Function
How to retrieve data from SQLDataReader using FieldNames in C# (.NET)
It is always better practice to use Field names instead of Index. You can decide which of the following is clear
string sPlayerName = rdr[1].ToString(); sPlayerName = rdr["PlayerFirstName"].ToString();
The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments
Parametrized Query in C# / .NET
How to pass parameters in SQL Queries in .NET (C#)
Parametrized queries are more secure (avoids SQL Injection etc) and easy to handle. The following example shows an simple example.
The above table has details of Players like name, contact details etc.
Let us try to get the details of players whose first name is 'Sachin'. First make a connection to database :
string sConString = GetConnectionString("TeamDBConnectionString"); SqlConnection Con = new SqlConnection(sConString); SqlCommand Cmd = new SqlCommand(); Cmd.Connection = Con; Con.Open();
Then set the CommandText property of SQLCommand and pass the parameters
String sSQLCmdText = "Select * from PlayerDetails where PlayerFirstName = @FirstName"; Cmd.CommandText = sSQLCmdText; Cmd.Parameters.AddWithValue("@FirstName", "Sachin");
Once this done, declare a SQLDataReader and get the rows into it
SqlDataReader rdr = Cmd.ExecuteReader(); while (rdr.Read() == true) { string sPlayerName = rdr.GetString(1); } Con.Close();
You can also pass the FieldName as parameter to query
SQLDataReader - Invalid attempt to read when no data is present
Wednesday, April 21, 2010
How to Add Generic List Items to ListBox in C# / VB.NET
We have already seen How to Add an ArrayList to ListBox. The following code shows how to add a C# Generic List to ListBox
public void Load_LB_GenericList() { ListTeam = new List (); ClassTeam CT = new ClassTeam(ClassTeam.playerType.Contract, "Sachin", 23, "33420242"); Team.Add(CT); CT = new ClassTeam(ClassTeam.playerType.Contract, "Sourav", 23, "33420242"); Team.Add(CT); CT = new ClassTeam(ClassTeam.playerType.Contract, "Dravid", 23, "33420242"); Team.Add(CT); listBox1.DataSource = Team; listBox1.DisplayMember = "Name"; listBox1.ValueMember = "Phone"; }
How to assign an ArrayList to ListBox in .NET (C#)
How to add ArrayList items to ListBox (VB.NET/C#) / How to Add Objects to ListBox using C# (.NET)
Let us consider an userform with a listbox. We now need to assign the Arraylist to the Listbox.
We go back to our Teamexample. We have a class called ClassTeam with following properties
Now we create objects of the above class and add it to an Arraylist
The arraylist 'Team' will nowcontain three ClassTeam objects.
Assign the ArrayList as datasource to the listbox and set the displaymember and valuemember
Some methods of ListBox will not be available when use DataSource.
Let us consider an userform with a listbox. We now need to assign the Arraylist to the Listbox.
We go back to our Teamexample. We have a class called ClassTeam with following properties
class ClassTeam { #region declarations public enum playerType { ClassA, ClassB, ClassC, Contract } private playerType _PlayerType; string _Name; int _Age; string _Phone; #endregion #region properties public playerType PlayerType { //accessor get { return _PlayerType; } //mutator set { _PlayerType = value; } } public string Name { get { return _Name; } set { _Name = value; } } public string Phone { get { return _Phone; } set { _Phone = value; } } public int Age { get { return _Age; } set { _Age = value; } } #endregion #region public methods public string SetPlayer() { return null; } #endregion #region ClassTeam Construct public ClassTeam(playerType PT, string sName, int iAge, string sPhone ) { PlayerType = PT; _Name= sName; _Age = iAge; _Phone = sPhone; } #endregion }
Now we create objects of the above class and add it to an Arraylist
ArrayList Team = new ArrayList(); ClassTeam CT = new ClassTeam(ClassTeam.playerType.Contract, "Sachin", 23, "33420242"); Team.Add(CT); CT = new ClassTeam(ClassTeam.playerType.Contract, "Sourav", 23, "33420242"); Team.Add(CT); CT = new ClassTeam(ClassTeam.playerType.Contract, "Dravid", 23, "33420242"); Team.Add(CT);
The arraylist 'Team' will nowcontain three ClassTeam objects.
Assign the ArrayList as datasource to the listbox and set the displaymember and valuemember
listBox1.DataSource = Team; listBox1.DisplayMember = "Name"; listBox1.ValueMember = "Phone";
Some methods of ListBox will not be available when use DataSource.
Items collection cannot be modified when the DataSource property is set.
Monday, April 19, 2010
How to iterate MultiSelect ListBox using C# (.NET)
C# - Get Selected Values from MultiSelect ListBox
Here is a way of retrieving the selected values of Multiselect listbox
for (int i1 = 0; i1 < listBox1.SelectedItems.Count; i1++) { DataRowView D1 = listBox1.SelectedItems[i1] as DataRowView; MessageBox.Show(D1[1].ToString()); }The above code uses SelectedItems collection to retrieve information
Saturday, April 17, 2010
How to Create MultiSelect Listbox in .NET (C#)
Enable MultiSelect in ListBox (C#/.NET)
Modifying the SelectionMode property of the listbox allows Multiple Items to be selected
Modifying the SelectionMode property of the listbox allows Multiple Items to be selected
How to get the selected value of listbox using C# code
The following code retrieves the value of listbox and the accompanying text
The above method retrieves the displaytext (DisplayMember) and the selected value (DisplayValue) from the selected item of listbox
private void listBox1_SelectedValueChanged(object sender, EventArgs e) { MessageBox.Show(listBox1.Text); MessageBox.Show(listBox1.SelectedValue.ToString()); }
The above method retrieves the displaytext (DisplayMember) and the selected value (DisplayValue) from the selected item of listbox
How to Bind DataSet to ListBox using C#
How to add items from database to Listbox control using C#
The following code binds the PlayerDetails table with the listbox
string sConString = GetConnectionString("TeamDBConnectionString"); SqlConnection Con = new SqlConnection(sConString); Con.Open(); //Command Text String sSQLCmdText = "Select * from PlayerDetails"; //Create a new SQL Data Adapter SqlDataAdapter DA = new SqlDataAdapter(sSQLCmdText , Con); DataSet DS = new DataSet("PlayerDS"); //DataSet DS.Clear(); DA.Fill(DS, "Player"); listBox1.DisplayMember = "PlayerName"; listBox1.ValueMember = "PlayerID"; listBox1.DataSource = DS.Tables["Player"]; Con.Close();
Friday, April 16, 2010
How to retrieve specific connection string from App.Config file using C# (.NET)
Get specific connection string from App.Config file using C# (.NET)
The connection string can be retrieved from the App.Config file using ConnectionStrings method of ConfigurationManager. You need to add the following directive in the code:
using System.Configuration;
The ConnectionStrings method without any arguments will return a collection of Connection strings in the App.Config file. If you want to retrieve specific ones you can either pass an index or string to it
private static string retsettings(String sConnName) { try { ConnectionStringSettings sConnection = ConfigurationManager.ConnectionStrings[sConnName]; return sConnection.ConnectionString; } catch (Exception ex1) { return null; } finally { } }
Wednesday, April 14, 2010
How to validate password using C# (.NET)
How to check password using C# Regular Expressions / How to enforce strong password using C# .NET
One of the common methods to check and validate password is through regular expressions. The criteria for strong password is :
1. Password should be minimum eight characters in length
2. Password should contain atleast a digit and an alphabet
3. Password should contain a non-alphanumeric character
The code uses Regular Expressions and hence the following directive is used:
using System.Text.RegularExpressions;
The code below checks for the length:
if (sPassword.Length < 8 ) { throw new Exception("Password should contain mimimum 8 chars"); }the code below checks for presence of atleast one number
sPattern = "\\d"; oReg = new Regex(sPattern, RegexOptions.IgnoreCase); if (oReg.IsMatch(sPassword) == false) { throw new Exception("Password should contain mimimum one numeric character"); }the code below checks for presence of atleast one alphabet
sPattern = "\\w"; oReg = new Regex(sPattern, RegexOptions.IgnoreCase); if (oReg.IsMatch(sPassword) == false) { throw new Exception("Password should contain mimimum one alphabet character"); }the code below checks for presence of atleast one non-alphanumeric character
string sPattern; sPattern = "[^a-zA-Z0-9\n\r\t ]"; Regex oReg = new Regex(sPattern, RegexOptions.IgnoreCase); if (oReg.IsMatch(sPassword) == false) { throw new Exception("Password should contain mimimum one non-alphanumeric character"); }Exceptions are raised and handled if the criteria is not matching
Monday, April 12, 2010
How to Raise Exceptions in C# / .NET
Raise Error in C# (.NET) / Throw Error/Exception in C# (.NET)
The following code generates an exception if the supplied text (password) is less than eight characters.
try { if (sPassword.Length < 8 ) { throw new Exception("Password should contain mimimum 8 chars"); } } catch(Exception ex1) { sMessage= ex1.Message.ToString(); return false; }
This way of raising user-defined exception helps in efficient way of handling exceptions
Sunday, April 11, 2010
How to Add an Array to List using C# /.NET
Add Range to List using C# / .NET
Let us take our own IPL example. The current IPL has eight teams that are part of the list
From next year two new teams- Pune and Kochi - will be part of IPL
Hence we are adding those two teams to an Array and adding the array using AddRange method
This will add Pune and Kochi to end of the list
Let us take our own IPL example. The current IPL has eight teams that are part of the list
ListlstIPLTeams = new List (); lstIPLTeams.Add("Mumbai Indians"); lstIPLTeams.Add("Chennai SuperKings"); lstIPLTeams.Add("Kolkatta KnightRiders"); lstIPLTeams.Add("Deccan Chargers"); lstIPLTeams.Add("Rajastan Royals"); lstIPLTeams.Add("Delhi DareDevils"); lstIPLTeams.Add("KingsXI Punjab"); lstIPLTeams.Add("RC Bangalore");
From next year two new teams- Pune and Kochi - will be part of IPL
Hence we are adding those two teams to an Array and adding the array using AddRange method
string[] NewIPLTeams = { "Pune", "Kochi" }; lstIPLTeams.AddRange(NewIPLTeams); Console.WriteLine("\nList After Add Range"); Console.WriteLine("======================="); foreach (string IPL in lstIPLTeams) { Console.WriteLine(IPL.ToString()); }
This will add Pune and Kochi to end of the list
How to Add and Sort Items in a list using C#
Adding and Sorting List Items using .NET (C#)
The following example creates a Generic list of IPL teams and sorts them
The following code does it:
Here is the output
The following example creates a Generic list of IPL teams and sorts them
The following code does it:
ListlstIPLTeams = new List (); lstIPLTeams.Add("Mumbai Indians"); lstIPLTeams.Add("Chennai SuperKings"); lstIPLTeams.Add("Kolkatta KnightRiders"); lstIPLTeams.Add("Deccan Chargers"); lstIPLTeams.Add("Rajastan Royals"); lstIPLTeams.Add("Delhi DareDevils"); lstIPLTeams.Add("KingsXI Punjab"); lstIPLTeams.Add("RC Bangalore"); Console.WriteLine("List Before Sorting"); Console.WriteLine("======================="); foreach (string IPL in lstIPLTeams) { Console.WriteLine(IPL.ToString()); } //Sort the Items lstIPLTeams.Sort(); Console.WriteLine("\nList After Sorting"); Console.WriteLine("======================="); foreach (string IPL in lstIPLTeams) { Console.WriteLine(IPL.ToString()); }
Here is the output
Friday, April 9, 2010
Private Constructors in C# / VB.NET
Use of Private Constructors in C# (.NET)
Here is an example of a Private Constructor
public class WicketCounter { //Private Constructor private WicketCounter() { } // No of Wickets public static int Wickets; // Public Method to Return the No of Wickets public static int WicketCount() { return ++Wickets; } }
The Class has a private constructor, a public static method and a static variable. The Method increments the Wicketcount (and hence the class itself is called wicketcounter) and the value is returned through Wickets var
WicketCounter.WicketCount(); MessageBox.Show(WicketCounter.Wickets.ToString());
The declaration of private constructor prevents the creation of default constructor. Hence the class cannot be instantiated and doesn;t contain any instance fields or methods
How to Download File from Website using C# (.NET)
How to Download File from Internet using C# (.NET)
private bool download_file_from_Net() { try { WebClient WC = new WebClient(); String sWebLocation = "http://logic.stanford.edu/talks/Web2.0/microsoft-logo.jpg"; String sLocalPath = "C:\\Temp\\New folder (2)\\microsoft-logo.jpg"; WC.DownloadFile(sWebLocation, sLocalPath); return true; } catch (Exception ex1) { return false; } }
Following errors might occur if you do not use the Destination File Name
For example
String sLocalPath = "C:\\Temp\\New folder (2)";
throws the following error
InnerException = {"Access to the path 'C:\\Temp\\New folder (2)' is denied."}
and
String sLocalPath = "C:\\Temp\\New folder (2)\\";
throws the following one
System.Net.WebException was caught
Message=An exception occurred during a WebClient request.
InnerException: System.IO.DirectoryNotFoundException
Message=Could not find a part of the path 'C:\Temp\New folder (2)\'.
Monday, April 5, 2010
How to Bind a Lisbox to Database in C# (.NET)
Bind Listbox to Dataset using Visual Studio
Following steps would help you in connected a database/dataset to the list box
Step1: Add a List Box control to the form and select the DataSource from quick edit
Step 2: Select appropriate data source type (We are going to connect to an SQL Server DB)
Step 3: Select Appropriate Database Model
Step 4: Add a connection to database and select appropriate DB
Step 5: Select appropriate field you want to show in listbox
A dataset will be created and will be used for it. You can write necessary code in listbox selectionchange events depending upon the business logic
Following steps would help you in connected a database/dataset to the list box
Step1: Add a List Box control to the form and select the DataSource from quick edit
Step 2: Select appropriate data source type (We are going to connect to an SQL Server DB)
Step 3: Select Appropriate Database Model
Step 4: Add a connection to database and select appropriate DB
Step 5: Select appropriate field you want to show in listbox
A dataset will be created and will be used for it. You can write necessary code in listbox selectionchange events depending upon the business logic
Switching Application Types using Visual Studio
Converting Application Types using Visual Studio
Visual Studio helps you to change Console Application to Windows Forms Application as shown below. This will help if you want to have your output on Console; then you can change the type from WinForms to console and view the o/p.
Visual Studio helps you to change Console Application to Windows Forms Application as shown below. This will help if you want to have your output on Console; then you can change the type from WinForms to console and view the o/p.
Saturday, April 3, 2010
Debug.Print and Debug.Assert in C#
VB Programmers would have used Debug.Print and Debug.Assert at will while debugging the code. These two statements come handy for efficient debugging of the code.
This can be done in C# using System.Diagnostics
missing the above directive will cause 'The name 'Debug' does not exist in the current context" error
This can be done in C# using System.Diagnostics
using System.Diagnostics;
missing the above directive will cause 'The name 'Debug' does not exist in the current context" error
int i1 = 0;
while (i1 < 10)
{
Debug.Assert(i1 != 3);
++i1;
}
Wednesday, March 31, 2010
System.IO.FileNotFoundException was unhandled
Program '..Sample.exe' has more than one entry point defined: '..Program.Main()'. Compile with /main to specify the type that contains the entry poin
The type or namespace name 'SoapFormatter' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'Soap' does not exist in the namespace 'System.Runtime.Serialization.Formatters' (are you missing an assembly reference?)
The type or namespace name 'SoapFormatter' could not be found (are you missing a using directive or an assembly reference?)
Add the following reference to the project to solve the error
The type or namespace name 'SoapFormatter' could not be found (are you missing a using directive or an assembly reference?)
Add the following reference to the project to solve the error
Tuesday, March 30, 2010
Accessors and mutators in C#
Accessors and mutators do the job of retrieving and storing the data to a class member. The class member will be usually private and hence cannot be accessed directly by the object.
The following code provides a hint of the same
Here _PlayerType is declared as private. This can be however accessed in the main program as shown below:
The statement CT.PlayerType = ClassTeam.playerType.Contract; Calls the Mutator (set property) and sets the value and CT.PlayerType.ToString() uses Get property and retrieves the value
The following code provides a hint of the same
public enum playerType { ClassA, ClassB, ClassC, Contract }
private playerType _PlayerType;
string Name;
string Age;
string Phone;
#endregion
#region properties
public playerType PlayerType
{
//accessor
get { return _PlayerType; }
//mutator
set
{
_PlayerType = value;
}
}
Here _PlayerType is declared as private. This can be however accessed in the main program as shown below:
ClassTeam CT = new ClassTeam();
CT.PlayerType = ClassTeam.playerType.Contract; //Calls the Mutator
MessageBox.Show(CT.PlayerType.ToString()); // Calls the Accessor
The statement CT.PlayerType = ClassTeam.playerType.Contract; Calls the Mutator (set property) and sets the value and CT.PlayerType.ToString() uses Get property and retrieves the value
Subscribe to:
Posts (Atom)