Convert DataTable to Generic List in C#

You could actually shorten it down considerably. You can think of the Select() extension method as a type converter. The conversion could then be written as this: List<Cards> target = dt.AsEnumerable() .Select(row => new Cards { // assuming column 0’s type is Nullable<long> CardID = row.Field<long?>(0).GetValueOrDefault(), CardName = String.IsNullOrEmpty(row.Field<string>(1)) ? “not found” : row.Field<string>(1), }).ToList();

How do you Sort a DataTable given column and direction?

I assume “direction” is “ASC” or “DESC” and dt contains a column named “colName” public static DataTable resort(DataTable dt, string colName, string direction) { DataTable dtOut = null; dt.DefaultView.Sort = colName + ” ” + direction; dtOut = dt.DefaultView.ToTable(); return dtOut; } OR without creating dtOut public static DataTable resort(DataTable dt, string colName, string direction) … Read more

JSF 2 dataTable row index without dataModel

Just bind the table to the view itself instead of to a bean. <h:dataTable binding=”#{table}” …> Then you can use #{table.rowIndex} where necessary. E.g. <h:column>#{table.rowIndex + 1}</h:column> Note that the code is as-is and that the EL variable name table is fully to your choice. See also: How does the ‘binding’ attribute work in JSF? … Read more

ComboBox.ValueMember and DisplayMember

You should not set datasource of your listbox and/or combobox in this order ComboBox1.DataSource = dataTable; ComboBox1.ValueMember = “id”; ComboBox1.DisplayMember = “name”; Instead, this is correct order: ComboBox1.ValueMember = “id”; ComboBox1.DisplayMember = “name”; ComboBox1.DataSource = dataTable; NOTE: setting datasource should be last line. If you set datasource first, SelectedIndexChanged event will fire and you may … Read more

How can I convert a DataTable to an XML file in C#?

You can use DataTable.WriteXml Method. Here is an example; How can i convert my datatable into XML using C# 2.0? string result; using (StringWriter sw = new StringWriter()) { dataTable.WriteXml(sw); result = sw.ToString(); } If you don’t actually need a string but read-only, processable XML, it’s a better idea to use MemoryStream and XPathDocument: XPathDocument … Read more