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
Related
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.
I have a datatable filled with a report from a web service. I am now trying to display the datatable in an datagridview. This is the code I use to build the datatable:
// Create DataTabe to handle the output
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("EmployeeFirstName");
dt.Columns.Add("EmployeeLastName");
dt.Columns.Add("DepartmentName");
dt.Columns.Add("DepartmentCode");
dt.Columns.Add("LocationName");
dt.Columns.Add("DivisionCode");
dt.Columns.Add("EarningName");
dt.Columns.Add("OTHours");
dt.Columns.Add("WorkDate")
Fill the new datatable:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(string.Join(",", row.ColumnValues));
}
Then I try to bind the data in the datatable to the dataGridview:
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
When I run the application it only displays the data from the first column in the datatable. Do I need a loop of sorts to work through the columns or am I just missing a step?
Yes that's cause you are adding only one value to your dt when you say dt.Rows.Add(string.Join(",", row.ColumnValues));. You should be doing something like below (assuming that ReportRow also has the columns with same names like "EmployeeFirstName" else change the names accordingly)
foreach (ReportRow row in report.Rows)
{
DataRow dr = dt.NewRow();
dr["EmployeeFirstName"] = row["EmployeeFirstName"];
dr["EmployeeLastName"] = row["EmployeeLastName"];
dr["DepartmentName"] = row["DepartmentName"];
//rest of the columns fill
//once all columns filled
dt.Rows.Add(dr);
}
dt.Rows.Add(string.Join(",", row.ColumnValues)); -> You can either add a single DataRow item or a array of objects.
From your call, you chose the later, you are adding a array of objects, except you are adding ONE SINGLE object.
string.Join(",", row.ColumnValues) is one object.
Well after sleeping I have found the issue with dropping it into an sql table... I didn't take into account that the export to a CSV and the addition of the " , " would affect the export to sql. Here is the modification of the lines of code that was the issue:
foreach (ReportRow row in report.Rows)
{
dt.Rows.Add(row.ColumnValues);
}
Thank you all for your responses!
i have 2 DataTables with Data (dtm and dtl).
I must find out if exist a DataRow from DataTable1 in Datatable2.
I have a combined primray key of 3 columns.
I know that i can get the DataTable primarykey like this.
DataColumn[] pkcol;
pkcol = dtm.PrimaryKey;
Is it possible to use the Find method like this?
if (dtl.Rows.Find(dtm[pkcol]) == null)
{
}
I must realize an DataTable Sync Method.
So i go foreach Datarow in dtm.Rows and Foreach Datarow in dtl.Rows.
It would be great if i can go ahead over the table and search for if exist the datarows primary key value in the table.
Any ideas?
Please help.
Thanks
According to MSDN DataRowCollection.Findalready is looking for rows with the given values in the PKs. So you don't even need to get the PKs, but simply an array of values, that matches the PKs in number and type:
// Create an array for the key values to find.
object[]findTheseVals = new object[3];
// Set the values of the keys to find.
findTheseVals[0] = "John";
findTheseVals[1] = "Smith";
findTheseVals[2] = "5 Main St.";
DataRow foundRow = table.Rows.Find(findTheseVals);
You would set the values to null to find your row.
I am iterating a DataTable in my C# code. I try to get the contents using of a column named "columnName" of row named "row" using -
object value = row["ColumnName"];
I get this error -
Error: System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.ArgumentException: Column 'FULL_COUNT' does not belong to table . at System.Data.DataRow.GetDataColumn(String columnName)
How is this possible ? My SQL query/result set has a column by that name and the query even runs in management studio.
How do I fix this error ?
I am guessing your code is iteration supposed to be something like this
DataTable table = new DataTable();
foreach (DataRow row in table.Rows) {
foreach (DataColumn col in table.Columns) {
object value = row[col.ColumnName];
}
}
If this is the case, row["ColumnName"] in each iteration looks for the same column with name ColumnName which obviously does not exists in your table.
The correct way is row[ColumnName] or row[col.ColumnName] in iteration above
I had a similar issue on my c# code, using a dataset which I had successfully initialized and populated with data from the DB.
So my return set was:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0]["systemLogo_img"]);
Of course the error was in t finding the column 'systemLogo_img'.
I noted that you simply do NOT have to call /qualify the column name. So the correction is:
data = new Byte[0];
data = (Byte[])(dataset.Tables[0].Rows[0].ItemArray[0]);
Simply put: use "ItemArray" at position.
Thanks
Do not write Gridview column names instead of Database column names.
dataGridViewEmployeeClass.Rows[n].Cells[0].Value = item["write the Database Column names"].ToString();
Try this, make sure your column name is same
DataTable dt = new DataTable();
dt.Columns.Add("abc", typeof(string));
DataRow dr = dt.NewRow();
dr["abc"]="";
I had a similar issue which was very basic to fix.
I was querying with a specific column name rather than Select * (i.e. Select Title). Beginner's error but happens to everyone.
If you want to check if the column exists in the DataRow before accessing the value the following block can help...
if (dataRow.Table.Columns.Contains("theColumnName"))
{
// do work
string text = string.Empty;
if (dataRow["theColumnName"] != System.DBNull.Value)
{
text = Convert.ToString(dataRow["theColumnName"]);
}
}
If it doesn't exist and it needs to be added to the data table you can add the column using #Karthick Ganesan's example
// add a column
dataTable.Columns.Add("theColumnName", typeof(string));
I had same issue was trying to pass two different keys for same product.
item.Product = SqlHelper.GetSafeString(dr, "ProductName");
item.Product = SqlHelper.GetSafeString(dr, "Product");
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"];