How to Convert Generic List To DataTable using C#

I have a task to need to get a DataTable, however, all existing objects are List, I need convert some of those lists to DataTables. Before I wrote my own code to do it. I searched internet and got 2 perfect articles which I need.

1: From DotNet Friends, By patriwala, Convert Generic List In To DataTable
   A simple and easy to use one, I adopted this solution.

2: Casting from a Collection to a Data Table using Generics and Attributes by Joseph Finsterwald

Here I copy some code from patriwala’s article:

/// <typeparam name=”T”>Custome Class </typeparam>
/// <param name=”lst”>List Of The Custome Class</param>
/// <returns> Return the class datatbl </returns>
public static DataTable ConvertTo<T>(IList<T> lst)
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item);

return tbl;

/// <summary>
/// </summary>
/// <typeparam name=”T”>Custome Class</typeparam>
/// <returns></returns>
public static DataTable CreateTable<T>()
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
return tbl;

And, how to use? Very easy, I show you my own sample:

List<SoldTerritories> listSoldTerritories = GetSoldTerritoriesList();
DataTable dt = ConvertTo<SoldTerritories>(listSoldTerritories);

That is!

Optimizing C#

I got part of content from

7 Ways To Optimize C# Code

1. Use StringBuilder or String ?

  StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.

However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
2. Comparing Non-Case-Sensitive Strings

if(str1.ToLower() == str2.ToLower()) …

But better use this way:

To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty

Try to replace lines like:

if (str == “”)


if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.

Note, there is a popular practice that checking a string’s length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>

5. Use && and || operators

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch

Using a try statement to keep code “simple” instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions

C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion.

Fill a pair of data (text and value) to ComboBox .NET 2.0 Windows Application

In .NET 2.0 Windows Application, It is not easy to fill a pair of data (text, value) to a ComboBox, Most of examples just introduced the Display member and value member:

comboBox1.DisplayMember = “Desc”;
comboBox1.ValueMember = “Code”;
comboBox1.DataSource = dt;

Now let us don’t use DataSource and DisplayMember way:

class CmdPairClass
private string _cmdLongStr;
public string CommandLongString
get { return _cmdLongStr; }
set { _cmdLongStr = value; }

private string _cmdShortStr;
public string CommandShortString
get { return _cmdShortStr; }
set { _cmdShortStr = value; }

public CmdPairClass(string s1, string s2)
this.CommandLongString = s1;
this.CommandShortString = s2;


public override string ToString()

return CommandLongString;

List<CmdPairClass> aCmdPairList = new List<CmdPairClass>();

public MForm()

aCmdPairList.AddRange( new CmdPairClass[] {
new CmdPairClass( “Power”, “PW” ),
new CmdPairClass( “Remote”, “RM”)


for (int i = 0; i < aCmdPairList.Count; i++)

this.cbCmdType.Items.Add(new CmdPairClass(aCmdPairList[i].CommandLongString, aCmdPairList[i].CommandShortString));


private void cbCmdType_SelectedIndexChanged(object sender, EventArgs e)
this.lbMessage.Items.Add(((CmdPairClass)this.cbCmdType.SelectedItem).CommandShortString + “\r\n”);



Public, Private, Protected and Internal in C#

Access Modifiers


All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. You specify the accessibility of a type or member when you declare it by using one of these access modifiers:


The type or member can be accessed by any other code in the same assembly or another assembly that references it. \


The type or member can only be accessed by code in the same class or struct.


The type or member can only be accessed by code in the same class or struct, or in a derived class.


The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

c# 类的public private internal protected的区别


public 修饰的类,可以在整个系统的任意地方调用,是完全公开的.

private 相反的,只能在类内部调用.任何实例,无法调用private调用.

internal 仅为同项目(这里的项目是只单独的项目,而不是整个解决方案)调用,按照我的理解,应该是和java的friendly一样的效果.

protected 自己及自己的子类可以调用


这三个修饰符如果修饰的都是类中的成员的话,public 修饰的成员可以被所有的类访问(本类,别的类,本类的子类),private修饰的成员只能被本类访问,protected修饰的成员只能被本类和本类的子类所访问。

Communicate with USB port using C#

I worked a GUI project using C# for an audio company. This project needs PC GUI program communicate with a hardware board which has a USB port so that the GUI and the board switch data.

The hardware board has a micro controller chip (MCU), Actually it is Microchip’s PIC. Then we know we can use PIC USB Bootloader in firmware side.

We can download Microchip’s software package about PICDEM Full Speed USB evaluation kit.

And, There is a good guide article from Evan:
PIC USB Bootloader using Microchip frimware and C#

Actually, our GUI program has little different way to communicate with PIC via USB port, let me find time to write later.

How to auto scroll to the bottom of a multiline TextBox in C# ?

At least in .NET 2.0, the TextBox control doesn’t have a property to let the TextBox automatically scroll to the bottom when it is set to multiline.

You have to write code like this:

textBox1.Text += “Test string \n”;
textBox1.SelectionStart = textBox1.Text.Length;

OR, you can use the following code:

textBox1.AppendText(“This is a test string \n”);
textBox1.SelectionStart = textBox1.Text.Length;

Call Javascript function from codebehind C#

How to call a javascript function from ASPX.cs code behind file?

Set the Body tag in your page/master page to runat=”server” and an id=”MainBody”.

Put the script tag in your page like you normally would with any HTML file
<script src=”popup.js”  type=”text/javascript”></script>

Then in the code behind attach the onload attribute to the body tag .

protected void Page_Load(object sender, EventArgs e)
MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl(“MainBody”);
MasterPageBodyTag.Attributes.Add(“Onload”, “Popup()”);

Or if you are using Master Pages where the body tag is in the Master Page. but only some of the content pages need to use the javascript.

You put this is the content pages that use the javascript.

protected void Page_Load(object sender, EventArgs e)
MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl(“MainBody”);
MasterPageBodyTag.Attributes.Add(“Onload”, “Popup()”);