Showing posts with label DataTable. Show all posts
Showing posts with label DataTable. Show all posts

Tuesday, April 26, 2011

DataTable move the Column

If I don't put the code here, I bet I'll never find it again when I need it ...





DataColumn dc = dtRatesManagerAll.Columns["RateId"];
dc.SetOrdinal(dtRatesManagerAll.Columns.Count - 1);



Tuesday, March 2, 2010

Enum to DataTable

I had a lot of ENUM-s and needed to make DataTable - s with the same structure for pretty much all of them.
I came up with this:




private static DataTable CreateDataTable < TheSQLtable > ()
{
Type t = typeof(TheSQLtable);
if (!t.IsEnum)
{
throw new InvalidOperationException("Type is not Enum");
}

DataTable dt = new DataTable();
dt.TableName = t.Name;
DataColumn dc;

string[] names = Enum.GetNames(t);
foreach (string name in names)
{
dc = new DataColumn();
dc.DataType = System.Type.GetType("System.String");
dc.ColumnName = name;
dc.Unique = false;
dt.Columns.Add(dc);
}

return dt;
}





(with a little help from stackoverflow)

Wednesday, February 24, 2010

How to check in C# if a DataRow is Empty. (nothing in any column)

I was hoping i find something like dr.isEmpty(), but there's nothing "this nice". So you do something plain like:





bool AreAllColumnsEmpty(DataRow dr)
{
if (dr == null)
{
return true;
}
else
{
foreach(var value in dr.ItemArray)
{
if (value != null)
{
if (value.ToString() != "")
{
return false;
}
}
}
return true;
}
}



Wednesday, August 20, 2008

DataTable C# Primary Key column .Contains

I needed to do something like use DataTable in C#, set Primary Key column, and later on maybe a "contains" ... to see if my set of ID is inside the DataTable
Anyways: this is how I did it:





DataTable myFilteredTerms = objSomethn.getresultsinDT ...
DataColumn[] myPrimaryKeyColumn = new DataColumn[1];
myPrimaryKeyColumn.SetValue(myFilteredTerms.Columns[0], 0);
myFilteredTerms.PrimaryKey = myPrimaryKeyColumn;

...

if (myFilteredTerms.Rows.Contains(intTheIdYouAreLookingFor))
{
...
}





(first column is the one with the ID-s ...)

as always, if you got pro or contra ... tell me bout it