DataTable to HTML Table C# code

C# DataTable to a HTML Table
Below is C# function to generate HTML table string from DataTable with custom options like Custom headers and Selected fields. “Format” in parameters will contain comma separated values like column1=column 1 name, column2=column 2 name and so on.


public static string DataTableToHtmlTable(DataTable TableData, string Format)
{
	try
	{
		Dictionary<string, string> mFormatDictionary = CSVtoDictionary(Format);
		StringBuilder mHtml = new StringBuilder();

		// change this with any delimiter you want
		int i = 0;
		
		List<int> mIndexes = new List<int>();

		mHtml.Append("<table style=\"width:100%\">");
		mHtml.Append("<tr>");
		for (i = 0; i < TableData.Columns.Count; i++)
		{
			if (Format.Contains(TableData.Columns[i].ColumnName))
			{
				mIndexes.Add(i);
				mHtml.Append("<th>" + mFormatDictionary[TableData.Columns[i].ColumnName] + "</th>");
			}
		}
		mHtml.Append("</tr>");

		foreach (DataRow row in TableData.Rows)
		{
			object[] array = row.ItemArray;

			mHtml.Append("<tr>");
			foreach (int mIndex in mIndexes)
			{
				mHtml.Append("<td>" + array[mIndex].ToString() + "</td>");
			}
			mHtml.Append("</tr>");

		}

		mHtml.Append("</table>");

		return mHtml.ToString();
		
	}
	catch (Exception exp)
	{
		throw exp;
	}
}

/* CSV to Dictionary utility function */
public static Dictionary<string, string> CSVtoDictionary(string Format)
{
	string[] mFormatArray = Format.Split(new char[] { ',' });
	Dictionary<string, string> mKVPair = new Dictionary<string, string>(mFormatArray.Length);

	foreach (string mFormatArrayItem in mFormatArray)
	{
		string[] mPair = mFormatArrayItem.Split(new char[] { '=' });
		mKVPair.Add(mPair[0], mPair[1]);
	}

	return mKVPair;
}

Leave a Reply

Your email address will not be published.