C# GenericParserAdapter is reading CSV Column name as Column1 - c#

I am trying to use GenericParserAdapter to read a CSV file into DataTable. And ColumnName is returning an incorrect value.
var adapter = new GenericParsing.GenericParserAdapter(outputFile.PathName);
DataTable dt = adapter.GetDataTable();
dt.Columns[0].ColumnName returns "Column1" which is not the actual name of that column. Not sure what I am doing wrong here.

Check out this:
reading a CSV into a Datatable without knowing the structure
it would appear that you need to set the parser FirstRowHasHeader = true
I am not sure if this can be done in your constructor, or if you will need to split
var adapter = new GenericParsing.GenericParserAdapter(outputFile.PathName);
Into multiple lines and define the parser attributes after instantiation.

Related

Set constant value to some columns in SqlBulkCopy

I'm trying transfer data from "csv" file to SQL Database. Is it possible to map some fields by default vale which not exsits in "csv" file?
Something like shown below:
bulkCopy.ColumnMappings.Add("Destenition_column_name", "constant_value");
Thanks for advance!
What about setting a default column BEFORE populating the DataTable?
var returnTable = new DataTable();
returnTable.Columns.Add("Constant_Column_Name").DefaultValue = "Constant_Value";
If you then add rows each row will always have the specified default value for this column without explicitly setting it.
Anytoe's answer can be useful if you create DataTable by yourself. But there could be a situation when you are getting the dataTable from some library method so you trick with default value will not work. For this case I found this solution:
var dt = await GetDataTable();
dt.Columns.Add("ImportFileId", typeof(long), importFileId.ToString());
This is a feature named "Expression Columns". For example, you can use this solution with the ExcelDataReader library which has ".dataset()" method.
And you always can just loop through the rows if you don't want to use "Expression Columns" :
foreach (DataRow dr in dt.Rows)
{
dr["ImportFileId"] = importFileId.ToString();
}
Info: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns

Filtering columns in datatable

I have a datatable with multiple columns. I want to filter the columns for which i do:
newDatableName= OldDt.ToTable(false,"col1","col2");
Now suppose, I want to specify the column names dyanamically i.e put all the column names in a string and then Do:
string colnames= "col1,col2";
newDatableName= OldDt.ToTable(false,colnames);
I tried the above but it does not work. I even tried:
string colname= "\"col1\",\"col2\"";
but it considers the string of column names as one column and gives the error that no such column present.
Any help appreciated.
I suppose that you are using the DataView.ToTable method (so OldDT is a DataView not a DataTable).
In this case you need to pass an array of your column names
string[] colnames = new string[] {"col1", "col2"};
newDatableName= OldDt.ToTable(false,colnames);
you can use Steve's answer, if don't like defining a new array try this:
string colnames="col1,col2"
newDatableName=OldDt.ToTable(colnames.Split(',');
DataTable.DefaultView.ToTable(bool, Params string[] ColumnNames);
The above Method creates and returns a new DataTable based on rows in an existing DataView.
You have to passes two parameters to this function.
If true, the returned DataTable contains rows that have distinct values for all its columns. The default value is false.
A string array that contains a list of the column names to be included in the returned DataTable . The DataTable contains the specified columns in the order they appear within this array.
For Example:
DataTable NewTable = dt.DefaultView.ToTable(false, "StartDate", "FinishDate", "ItemName", "AssigneeNames", "ProjectName", "PercentComplete");

Get Dataset information in C#

I have an Dataset (XSD) with many datatables. How can I get informations about this datatables? for example I want to get all columns and its captions from a specific datatable.
When I use dataset_X.datatable_Y.... there are no properties like "colums" and so on.
I only get "Equals", "GetDataTableSchema", "GetTypedSchema" and "Reference Equals".
You need to create an instance of your strongly typed DataSet.
For example:
var ds = new dataset_X();
DataColumnCollection columns = ds.datatable_Y.Columns;
or, if you want informations of a specific column, you can also use the auto generated property. Assuming there's a column with a name idSparePart, there's automatically a property idSparePartColumn.
DataColumn col = ds.datatable_Y.idSparePartColumn;
String columnName = col.ColumName;
Type t = col.DataType;
// and so on...
You can try with this code - based on GetXmlSchema
string schemaString = dataSet.GetXmlSchema();
Link : http://msdn.microsoft.com/en-us/library/41732z18.aspx

How to get unique records of specific columns of data table

I have a DataTable imported from Excel file.
Data i need is only unique from specific columns of the DataTable.
The unique data i meant is like when a command DISTINCT is used in SQL Select Query.
I want to get the list of the unique data from the DataTable Column and put them into List
I think LinQ can be used for this matter but i'm not so familiar with it.
I was thinking of code like this below
var data is from MyDataTable
where MyDataTable.ColumnName = "SpecificColumn"
select MyDataTable["SpecificColumn"]).UniqueData;
List<string> MyUniqueData = new List<string>();
foreach(object obj in data)
{
if(MyUniqueData.NotContain(obj))
MyUniqueData.add(obj);
}
I hope someone can drop off some knowledge to me.
var unique = data.Distinct().ToList();
What you're looking for is .Distinct(). See MSDN documentation here. You can specify your own comparer if you need something specific and it will return only unique records.
If you have a Datatable or DataView, inorder to get unique records from a column, you have to write this.
this would be simple.
DataTable dtNew = dt.DefaultView.ToTable(true, "ColName"); // for Datatable
DataTable dtnew= dv.ToTable(true, "ColName"); // for DataView

How can I add the column data type after adding the column headers to my datatable?

Using the code below (from a console app I've cobbled together), I add seven columns to my datatable. Once this is done, how can I set the data type for each column? For instance, column 1 of the datatable will have the header "ItemNum" and I want to set it to be an Int. I've looked at some examples on thet 'net, but most all of them show creating the column header and column data type at once, like this:
loadDT.Columns.Add("ItemNum", typeof(Int));
At this point in my program, the column already has a name. I just want to do something like this (not actual code):
loadDT.Column[1].ChangeType(typeof(int));
Here's my code so far (that gives the columns their name):
// get column headings for datatable by reading first line of csv file.
StreamReader sr = new StreamReader(#"c:\load_forecast.csv");
headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
loadDT.Columns.Add(header);
}
Obviously, I'm pretty new at this, but trying very hard to learn. Can someone point me in the right direction? Thanks!
You should be able to assign the column's data type property so long as there is no data stored in that column yet:
CODE:
loadDT.Column[1].DataType = typeof(int);
visual studio not allows to change type of a column has some data,
u must create a new column with ur ideal type and copy data from specified column to new column
DataTable DT = new DataTable();
DT = somsdata ;
DT.columns.Add("newcol",object);
foreach(datarow dr in DT.rows)
dr.itemarray["newcolumn"] = dr.itemarray["oldColumn"];

Categories