I am pretty sure this is not possible but I will ask for clarification.
I am using ExcelLibrary in C# to convert a dataset into an Excel document. I recently had the requirement to add a string to the end of the excel document in every file. I simply added two new rows to the datatable (one empty and the second row displayed the string in the first cell).
I got a bug report today because in one particular excel document the first column displays the ID (something unusual in the system) and I get the error:
Input string was not in a correct format.Couldn't store <**mystring**> in id Column. Expected type is Int32.
I am pretty sure I cannot add my string to this column and I need to add it to a different column which is a nvarchar, but does anyone have any suggestions to resolve this problem?
edit: the code for anyone who may require it
DataRow dr = ds.Tables[0].NewRow();
ds.Tables[0].Rows.Add(dr);
DataRow dr2 = ds.Tables[0].NewRow();
dr2[0] = System.Configuration.ConfigurationManager.AppSettings["excelString"];
ds.Tables[0].Rows.Add(dr2);
The dataset I am working with is directly from a query in the database and the first column is an INT
Related
I have a .csv file that I am trying to load into a DataGridView. First, I have a combobox that will hold all of the values in the first column of the .csv. The user will select one item from the combobox, and my code is supposed to then search for that item, retrieve the other elements from the same row, and place them into a datagridview. From the examples I've seen, there is always a header in each column that can be referenced, however the .csv file I am working with will have no headers. How can I reference these columns within a OleDbCommand?
I've tried pulling the whole file into a dataset, and then manipulating the dataset to use just the first column, but without column headers I'm not certain how to actually pull specific columns.
{
myConn.Open();
var objCmd = new OleDbCommand("SELECT * FROM [myFileName.csv]", myConn);
OleDbDataAdapter objDA = new OleDbDataAdapter();
objDA.SelectCommand = objCmd;
DataSet ObjDataSet = new DataSet();
objDA.Fill(ObjDataSet);
DefaultSelector.DataSource = ObjDataSet.Tables[0].Columns[];
}
With the above I get an error: "Complex DataBinding accepts as a data source either an IList or an IListSource".
I've tried using Rows[0] instead of Columns[0], attempting to get the first item of each row, but it seems that i would also need to include a ["HeaderName"] following it, which doesn't exist in the file.
Is it possible to just pull one column from the .csv? If not, how can I pull 1 column from the DataSet?
Very late on this, but...
Just use F1, F2, F3, ... as column names in the query.
select F3 from MyFile.CSV where F1='some_id'
I think the 'F' stands for Field.
I have a datatable and I am masking one column by adding new column name as MASKEDSSN.
It has been masked. But i need to Remove Old Column name SSN. While Removing it throws an error as
Cannot remove this column, because it is part of an expression:
MaskedSSN = 'XXX-XX-'+SUBSTRING(CONVERT(SSN, System.String),6,4).
Code:
DataTable employeeTable = new DataTable();
employeeTable.Rows.Add("123455789");
employeeTable.Rows.Add("123447789");
employeeTable.Rows.Add("823456719");
employeeTable.Columns.Add("SSN");
int index = employeeTable.Columns["SSN"].Ordinal;
employeeTable.Columns.Add("MaskedSSN", typeof(string));
employeeTable.Columns["MaskedSSN"].Expression = "'XXX-XX-
'+SUBSTRING(CONVERT(SSN, System.String),6,4)";
DataTable newsss = new DataTable();
newsss = employeeTable.Copy();
newsss.AcceptChanges();
newsss.Columns.RemoveAt(index);
newsss.Columns.Remove("SSN");
You are using Expression syntax to build MaskedSSN
employeeTable.Columns["MaskedSSN"].Expression = "'XXX-XX-
'+SUBSTRING(CONVERT(SSN, System.String),6,4)";
If you make masking manually with AddRow, you can delete old SSN Column.
Edit
Func<string, string> MaskingFnc = (string ssnParam) => string.Format("XXX-XX-{0}", ssnParam.Substring(4,6));
DataTable employeeTable = new DataTable();
employeeTable.Columns.Add("SSN")
employeeTable.Columns.Add("SSNMasked")
employeeTable.Rows.Add("123455789", MaskingFnc("123455789"));
employeeTable.Rows.Add("123447789", MaskingFnc("123447789"));
employeeTable.Rows.Add("823456719", MaskingFnc("823456719"));
Expressions, or computed columns, relies on the source column to have the data in, because it is referencing the data, it doesn't COPY the data and then mask it.
So if your original column data changes, the new column will automatically have the same value.
When you understand this dependency, you will realize that you can't just remove the source column, because if you do, you will have a null reference exception happening. Think of it as excel spreadsheet. Column A has a value, Column B uses Column A's value to determine a percentage (or show it in a currency format). If you delete Column A, Columb B will immediately get an error (#REF! or something)
Your question on CodeProject has more detail, which would be appreciated on StackOverflow too: https://www.codeproject.com/Questions/1272445/Cannot-remove-this-column-because-it-is-part-of-an
In there, you show you try to copy the table, and then remove the column from it, while still having the expression, which results in an error.
Hopefully my explanation highlights the dependency between a column and a computed column/expression.
I would suggest formatting the data in the front-end (that's why we have front-end), or, if it's part of an API, format it in the SQL output.
Any input can also be masked so that data is inserted correctly BEFORE having to read it out anywhere.
You can mask manually using string.Format (note, below might not compile, I leave it to you to figure out)
string result = string.Format("XXX-XX-{0}", SSNColumnValue.Substring(4,6));
Hope this helps guide you in the right direction
I wrote a parser that takes some information from Excel sheets using the Spire.xls library and then writes the information to another Excel file.
I'm running into a weird problem. For some reason the program is taking serial numbers such as
03-02281
03-02282
03-01975
And writing them into the Excel sheet as
3/1/2281
3/1/2282
3/1/1975
This only happens with some values.
Others such as
30-04761
03-00613
03-00614
are transcribed unchanged.
I checked in the excel file, the fields are set as text format. So they were either stored that way originally or Excel is interpreting the serial numbers to be dates. Other possibility is that it doesn't happen in the original file and the text is not automatically corrected/changed if I manually type in the correct values.
Does anyone know why this is happening and how I can tell Excel to just treat these as text and nothing else?
I though about appending a ' to them in the beginning of each value, but these have to then be read by other parsers so it's not the most convenient option.
Edit:
Here's some ofthe code I use for this, hopefulyl it can give you guys an idea of where I'm going wrong.
This is the code that adds all the values:
Workbook workbook = new Workbook();
workbook.LoadFromFile(templateExcelFileUri);
Worksheet sheet = workbook.Worksheets[0];
int ColumnIndex = 0; //for the datatable columns iteration
int columnCounter = 1; //for the excel sheet columns iteration
int ColumnsToAdd = 6; //(Seccion, seccion desc, marca, marca desc, **IdArticulo**, articulo desc)
//get the data of the new column
DataColumn DescriptionsDataColumn;
//First, add the suggestions.
for (; ColumnIndex < ColumnsToAdd; ColumnIndex++,
columnCounter++)
{
sheet.InsertColumn(columnCounter);
if(columnCounter==5)
sheet.Columns[5].NumberFormat = "#";// the column with the serial numbers.
DescriptionsDataColumn = AutomatController.DescriptionsTable.Columns[ColumnIndex];
//insert the data into the new column
sheet.InsertDataColumn(DescriptionsDataColumn, true, 2, columnCounter);
}
And for references, the table the values of which I add:
public static void SetDescriptionsTable()
{
DescriptionsTable.Columns.Add("Seccion", typeof(string));
DescriptionsTable.Columns.Add("SeccionDescripcion", typeof(string));
DescriptionsTable.Columns.Add("Marca", typeof(string));
DescriptionsTable.Columns.Add("MarcaDescripcion", typeof(string));
DescriptionsTable.Columns.Add("IdArticulo", typeof(string)); //Serial numbers
DescriptionsTable.Columns.Add("ArticuloDescripcion", typeof(string));
}
Thanks for the edits to the format of my question and the title. I'm still a little new here and I'm learning how to do that better.
The reason why some values do not map to dates is because they fall outside of the format MM-dyyyy format. for example there is no month 30 (30-02281) or day 0 (03-01975).
I think the only thing you need to do is set the format of the target column and cell prior to setting its value through the API. Sometimes cloning a column or a cell defaults the formatting to "Auto" and Excel tries to be too smart.
If you can share a bit of your code the community may be able to more accurately diagnose the problem.
You should set the columns format to general before setting the value.
I can't seem to be able to be access elements that my DataRow has pulled from my DataTable, I haven't had that much practice with c# either
This is my code:
DataRow[] results = dt.Select("[Acc No] = '"+ search +"'");
I have tried casting teh objects from datarow to a string but that was not working.
Search is just a string from a textbox.
When debugging i can see the items array with all the data in it so i know the select is working, can anyone help?
You need to provide more code that that... Such as how you're trying to access the contents of a DataRow. To get a value out of the row, I believe the syntax would be something like results[rowNumber][columnNumber/name]
I.e. results[0][0] to get the first column value out of the first row, or results[0]["Id"] to get the "Id" column from the first row.
Of course you should check results.Count() before attempting to access the DataRow array.
I'm trying to edit the data in a dataset (change the value in a column on one row), which is not linked to a database. I've been googling for about an hour with no results and no good examples out there. Hopefully someone can help me.
My table (DataTable1) has these columns - ThreadID (string, PK), StatusText (string).
I can select a row in a DataGridView, and get the ThreadID value. No matter how I've tried to edit the row in the associated dataset, either nothing happens or I get an error. Here's what I have now:
string sThreadID = "";
sThreadID = gridThreads.Rows[gridThreads.CurrentRow.Index].Cells["ID"].Value.ToString(); // gives me a good id, which is in the dataset
DataRow drRow = dataThreads.Tables["DataTable1"].Rows.Find(sThreadID);
drRow["StatusText"] = "Test";
The error I get when getting the row (3rd line) is: "Object reference not set to an instance of an object.". I can't create a new DataRow object because there's no public constructor for it (according to my research).
I'm sure I'm missing something basic, but I'm not familiar with working with datasets. What am I doing wrong? Thanks for your help.
How does drRow know what "statusText" is? You may be only getting a shalllow copy, try cloning/copy so that the data types of the row get copied as well. Just an idea.
Does it happen that dataThreads or Tables["DataTable1"] is null ?
To create a new row, use the NewRow() method of the data table.