I need to create an Excel file in which the user can later adjust a specific information. I'm using C# and EPPlus v6.0.4. For example, if the input is a list of products, I want it to be joined with ' taxes included' string (which can be later changed by the user at Excel):
descriptionA -> descriptionA taxes included
descriptionB -> descriptionB taxes included
descriptionC -> descriptionC taxes included
I'm assuming two worksheets: ws1 (parameter) and ws2 (output list). As shown below, cell B1 is where the user will be able to change the "taxes included" string.
ws1.Cells["A1"].Value = "Additional information:";
excel.Workbook.Names.Add("auxData", ws1.Cells["B1"]);
ws1.Cells["B1"].Value = " taxes included 12%";
At the second worksheet (ws2) I will have the data being populated.
int excelLine = 1;
foreach (var product in productList)
{
string productDescription = product.Description;
ws2.Cells["A" + excelLine].Formula = .....; //need ideas on how to solve this
excelLine ++;
}
At the above .Formula I was trying CONCAT or similar function but its not working (excel file is generated with errors or the formula is not accepted).
The expected output is a cell value ="product full description variable string" & auxData, therefore suitable to B1 text changes by the user (auxData is an Excel name to =ws1!$B$1).
My own solution was:
int excelLine = 1;
foreach (var product in productList)
{
string cellDescription = "=\"" + product.Description + " -- additional information \" & auxData & \"%\"";
ws2.Cells["A" + excelLine].Formula = cellDescription;
excelLine ++;
}
That consist of 2 columns: roomType and no rooms
So I want to get no rooms value from room type that i have.
In SQL its look like this:
SELECT no_rooms from table name where roomtype = 'deluxe'
Result: 2
How to access that in LINQ query and store that value as int datatype?
I only know this code
string[] tableName = table.AsEnumerable()
.Select(s => s.Field<string>("NoRooms"))
.ToArray<string>()
.Where(?idont_know_the_query));
var results = from myRow in table.AsEnumerable()
where myRow.Field<String>("roomtype ") == "deluxe"
select myRow;
Here is just another way of retriving the data rows, assuming that table in your example is a DataTable
string expression = string.Format("roomtype='{0}'","deluxe");
var rows = dt.Select(expression);
var strRoomNumber = rows.Select(r=>r.Field<string>("roomNumber")).FirstOrDefault();
int no_rooms;
int.TryParse(strRoomNumber,out no_rooms);
This will return you the first no of rooms for the first matching record
var NoOfRooms= tablename.where(x=>x.roomType=="deluxe").ToList();
int total = NoOfRooms.count();
I have a DataTable, which I construct in the following way:
DataTable data = new DataTable();
data.Columns.Add("year");
data.Columns.Add("month");
data.Columns.Add("id");
data.Columns.Add("displayText");
data.Columns["displayText"].Expression = "Convert(year, 'System.String') + ' / ' + Convert(month , 'System.String')";
DataColumn[] keyColumns = new DataColumn[2];
keyColumns[0] = data.Columns["year"];
keyColumns[1] = data.Columns["month"];
data.PrimaryKey = keyColumns;
data is used as a data source for the monthList drop down list
this.monthList.DataTextField = "displayText";
this.monthList.DataValueField = "id";
this.monthList.DataSource = data;
this.monthList.DataBind();
Then I have an event handler, in which I need to extract both components of the key column.
How can I do that?
I tried to use monthList.SelectedItem.Value, but it contains a string "System.Object[]".
Update 1: Here's the debugger's screenshot.
Update 2: Here's how I add items to data:
var row = data.NewRow();
row["year"] = 2014;
row["month"] = 5;
row["id"] = new object[] { 2014, 5 };
data.Rows.Add(row);
Not sure why you are trying to store an array in your id field considering that the same values are stored in the same row but in different columns, but you could extract the values in that field if you declare your column of type object
data.Columns.Add("id", typeof(object));
and then retrieve them with
object[] ids = (object[])data.Rows[0]["id"];
for(int x = 0; x < ids.Length; x++)
Console.WriteLine(Convert.ToInt32(ids[x]));
You have set:
this.monthList.DataValueField = "id";
Therefore the Value property will be set to the value of the "id" column in your DataTable.
The "id" column in your DataTable is defined (by default) as type "String", but you've set it to an object array:
row["id"] = new object[] { 2014, 5 };
The column will actually contain
(new object[] { 2014, 5 }).ToString();
which is the string you're seeing.
You could try declaring the id column as type object[]:
dt.Columns.Add("id", typeof(object[]));
After which you should be able to cast monthList.SelectedItem.Value to object[] and extract your two values.
Having said that: personally I would probably put the two values composing the id into separate int columns.
It seems that binding a column that contains collection of objects to DataValueField property of DropDownList is not supported by design(it makes value attribute of option tag to be set to collection type name).
You could try to dump collection objects to a single string value and use that string value as a key...
For example:
row["id"] = "2014_05";
EDIT:
Of course you may calculate this key value automatically using the same feature as you used for displayText column:
data.Columns["id"].Expression = "Convert(year, 'System.String') + '_' + Convert(month , 'System.String')";
I am using a datatable created by program. In this datatable i want to insert values in some specified columns.
Initially I am inserting primary key values leaving remaining columns null, when I am querying datatable with recently inserted value in Primary column to update same row, I am facing error Missing operand after ID operator
Can any one tell me the exact issue.
I am trying following code:
dt.Rows.Add(1);
int insertedValue = 1;
DataRow[] dr = dt.Select("ID = '" + insertedValue.toString() + "'");
And the table structure after entring primary value is as follows.
ID Volumn1 Volumn2 volumn3
--------------------------------------
1
You can do this more cleanly with LINQ and make this a strongly typed operation.
Something like:
dt.Rows.Add(1);
int insertedValue = 1;
var result =
dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == insertedValue );
Working example:
DataTable dt = new DataTable();
dt.Columns.Add( "ID", typeof( int ) );
dt.Rows.Add( 1 );
var result = dt.AsEnumerable().Where( dr => dr.Field<int>( "ID" ) == 1 );
You can simply format the selection string as shown below:
DataRow[] dr = dt.Select(string.Format("ID ='{0}' ", insertedValue));
Feel free to let me know if this works for you.. Thanks
You do not need ' ' in your filter.
I think this should work:
DataRow[] dr = dt.Select("ID = " + insertedValue.toString());
By the way, reference System.Data.DataSetExtensions
If you are looking for a specific row and your datatable has a primary key you could use the Find method and target the primary key which would return just the row you want rather than an array:
DataRow foundRow = dt.Rows.Find([INSERT SEARCH PARAMETER HERE]);
if(foundRow != null)
{
TO SET A STRING EQUAL TO A FOUND VALUE:
string str = foundRow["COLUMN NAME / INDEX];
OR IF YOU ARE INSERTING A VALUE YOU CAN USE IT LIKE THIS:
foundRow["COLUMN NAME / INDEX"] = NEW VALUE;
}
select column of row
dt.Rows[0].Field<string>("MyColumnName")
I have a C# code which does lot of insert statements in a batch. While executing these statements, I got "String or binary data would be truncated" error and transaction roledback.
To find out the which insert statement caused this, I need to insert one by one in the SQLServer until I hit the error.
Is there clever way to findout which statement and which field caused this issue using exception handling? (SqlException)
In general, there isn't a way to determine which particular statement caused the error. If you're running several, you could watch profiler and look at the last completed statement and see what the statement after that might be, though I have no idea if that approach is feasible for you.
In any event, one of your parameter variables (and the data inside it) is too large for the field it's trying to store data in. Check your parameter sizes against column sizes and the field(s) in question should be evident pretty quickly.
This type of error occurs when the datatype of the SQL Server column has a length which is less than the length of the data entered into the entry form.
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters. that's why you faced this type of error in this code
Generally it is that you are inserting a value that is greater than the maximum allowed value. Ex, data column can only hold up to 200 characters, but you are inserting 201-character string
BEGIN TRY
INSERT INTO YourTable (col1, col2) VALUES (#val1, #val2)
END TRY
BEGIN CATCH
--print or insert into error log or return param or etc...
PRINT '#val1='+ISNULL(CONVERT(varchar,#val1),'')
PRINT '#val2='+ISNULL(CONVERT(varchar,#val2),'')
END CATCH
For SQL 2016 SP2 or higher follow this link
For older versions of SQL do this:
Get the query that is causing the problems (you can also use SQL Profiler if you dont have the source)
Remove all WHERE clauses and other unimportant parts until you are basically just left with the SELECT and FROM parts
Add WHERE 0 = 1 (this will select only table structure)
Add INTO [MyTempTable] just before the FROM clause
You should end up with something like
SELECT
Col1, Col2, ..., [ColN]
INTO [MyTempTable]
FROM
[Tables etc.]
WHERE 0 = 1
This will create a table called MyTempTable in your DB that you can compare to your target table structure i.e. you can compare the columns on both tables to see where they differ. It is a bit of a workaround but it is the quickest method I have found.
It depends on how you are making the Insert Calls. All as one call, or as individual calls within a transaction? If individual calls, then yes (as you iterate through the calls, catch the one that fails). If one large call, then no. SQL is processing the whole statement, so it's out of the hands of the code.
I have created a simple way of finding offending fields by:
Getting the column width of all the columns of a table where we're trying to make this insert/ update. (I'm getting this info directly from the database.)
Comparing the column widths to the width of the values we're trying to insert/ update.
Assumptions/ Limitations:
The column names of the table in the database match with the C# entity fields. For eg: If you have a column like this in database:
You need to have your Entity with the same column name:
public class SomeTable
{
// Other fields
public string SourceData { get; set; }
}
You're inserting/ updating 1 entity at a time. It'll be clearer in the demo code below. (If you're doing bulk inserts/ updates, you might want to either modify it or use some other solution.)
Step 1:
Get the column width of all the columns directly from the database:
// For this, I took help from Microsoft docs website:
// https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.getschema?view=netframework-4.7.2#System_Data_SqlClient_SqlConnection_GetSchema_System_String_System_String___
private static Dictionary<string, int> GetColumnSizesOfTableFromDatabase(string tableName, string connectionString)
{
var columnSizes = new Dictionary<string, int>();
using (var connection = new SqlConnection(connectionString))
{
// Connect to the database then retrieve the schema information.
connection.Open();
// You can specify the Catalog, Schema, Table Name, Column Name to get the specified column(s).
// You can use four restrictions for Column, so you should create a 4 members array.
String[] columnRestrictions = new String[4];
// For the array, 0-member represents Catalog; 1-member represents Schema;
// 2-member represents Table Name; 3-member represents Column Name.
// Now we specify the Table_Name and Column_Name of the columns what we want to get schema information.
columnRestrictions[2] = tableName;
DataTable allColumnsSchemaTable = connection.GetSchema("Columns", columnRestrictions);
foreach (DataRow row in allColumnsSchemaTable.Rows)
{
var columnName = row.Field<string>("COLUMN_NAME");
//var dataType = row.Field<string>("DATA_TYPE");
var characterMaxLength = row.Field<int?>("CHARACTER_MAXIMUM_LENGTH");
// I'm only capturing columns whose Datatype is "varchar" or "char", i.e. their CHARACTER_MAXIMUM_LENGTH won't be null.
if(characterMaxLength != null)
{
columnSizes.Add(columnName, characterMaxLength.Value);
}
}
connection.Close();
}
return columnSizes;
}
Step 2:
Compare the column widths with the width of the values we're trying to insert/ update:
public static Dictionary<string, string> FindLongBinaryOrStringFields<T>(T entity, string connectionString)
{
var tableName = typeof(T).Name;
Dictionary<string, string> longFields = new Dictionary<string, string>();
var objectProperties = GetProperties(entity);
//var fieldNames = objectProperties.Select(p => p.Name).ToList();
var actualDatabaseColumnSizes = GetColumnSizesOfTableFromDatabase(tableName, connectionString);
foreach (var dbColumn in actualDatabaseColumnSizes)
{
var maxLengthOfThisColumn = dbColumn.Value;
var currentValueOfThisField = objectProperties.Where(f => f.Name == dbColumn.Key).First()?.GetValue(entity, null)?.ToString();
if (!string.IsNullOrEmpty(currentValueOfThisField) && currentValueOfThisField.Length > maxLengthOfThisColumn)
{
longFields.Add(dbColumn.Key, $"'{dbColumn.Key}' column cannot take the value of '{currentValueOfThisField}' because the max length it can take is {maxLengthOfThisColumn}.");
}
}
return longFields;
}
public static List<PropertyInfo> GetProperties<T>(T entity)
{
//The DeclaredOnly flag makes sure you only get properties of the object, not from the classes it derives from.
var properties = entity.GetType()
.GetProperties(System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.DeclaredOnly)
.ToList();
return properties;
}
Demo:
Let's say we're trying to insert someTableEntity of SomeTable class that is modeled in our app like so:
public class SomeTable
{
[Key]
public long TicketID { get; set; }
public string SourceData { get; set; }
}
And it's inside our SomeDbContext like so:
public class SomeDbContext : DbContext
{
public DbSet<SomeTable> SomeTables { get; set; }
}
This table in Db has SourceData field as varchar(16) like so:
Now we'll try to insert value that is longer than 16 characters into this field and capture this information:
public void SaveSomeTableEntity()
{
var connectionString = "server=SERVER_NAME;database=DB_NAME;User ID=SOME_ID;Password=SOME_PASSWORD;Connection Timeout=200";
using (var context = new SomeDbContext(connectionString))
{
var someTableEntity = new SomeTable()
{
SourceData = "Blah-Blah-Blah-Blah-Blah-Blah"
};
context.SomeTables.Add(someTableEntity);
try
{
context.SaveChanges();
}
catch (Exception ex)
{
if (ex.GetBaseException().Message == "String or binary data would be truncated.\r\nThe statement has been terminated.")
{
var badFieldsReport = "";
List<string> badFields = new List<string>();
// YOU GOT YOUR FIELDS RIGHT HERE:
var longFields = FindLongBinaryOrStringFields(someTableEntity, connectionString);
foreach (var longField in longFields)
{
badFields.Add(longField.Key);
badFieldsReport += longField.Value + "\n";
}
}
else
throw;
}
}
}
The badFieldsReport will have this value:
'SourceData' column cannot take the value of
'Blah-Blah-Blah-Blah-Blah-Blah' because the max length it can take is
16.
It could also be because you're trying to put in a null value back into the database. So one of your transactions could have nulls in them.
Most of the answers here are to do the obvious check, that the length of the column as defined in the database isn't smaller than the data you are trying to pass into it.
Several times I have been bitten by going to SQL Management Studio, doing a quick:
sp_help 'mytable'
and be confused for a few minutes until I realize the column in question is an nvarchar, which means the length reported by sp_help is really double the real length supported because it's a double byte (unicode) datatype.
i.e. if sp_help reports nvarchar Length 40, you can store 20 characters max.
Checkout this gist.
https://gist.github.com/mrameezraja/9f15ad624e2cba8ac24066cdf271453b.
public Dictionary<string, string> GetEvilFields(string tableName, object instance)
{
Dictionary<string, string> result = new Dictionary<string, string>();
var tableType = this.Model.GetEntityTypes().First(c => c.GetTableName().Contains(tableName));
if (tableType != null)
{
int i = 0;
foreach (var property in tableType.GetProperties())
{
var maxlength = property.GetMaxLength();
var prop = instance.GetType().GetProperties().FirstOrDefault(_ => _.Name == property.Name);
if (prop != null)
{
var length = prop.GetValue(instance)?.ToString()?.Length;
if (length > maxlength)
{
result.Add($"{i}.Evil.Property", prop.Name);
result.Add($"{i}.Evil.Value", prop.GetValue(instance)?.ToString());
result.Add($"{i}.Evil.Value.Length", length?.ToString());
result.Add($"{i}.Evil.Db.MaxLength", maxlength?.ToString());
i++;
}
}
}
}
return result;
}
With Linq To SQL I debugged by logging the context, eg. Context.Log = Console.Out
Then scanned the SQL to check for any obvious errors, there were two:
-- #p46: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value1]
-- #p8: Input Char (Size = -1; Prec = 0; Scale = 0) [some long text value2]
the last one I found by scanning the table schema against the values, the field was nvarchar(20) but the value was 22 chars
-- #p41: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [1234567890123456789012]
In our own case I increase the sql table allowable character or field size which is less than the total characters posted from theĀ front end. Hence that resolve the issue.
Simply Used this:
MessageBox.Show(cmd4.CommandText.ToString());
in c#.net and this will show you main query , Copy it and run in database .