Converting DateTime data to String in dataset - asp.net

I have a dataset which stores dates in a DataColumn (datatype of this column is DateTime). I need to change the format from DateTime to string that will give me the date as per my current culture.
In case of a single DateTime variable, I can use the overloaded ToString() to achieve this in the following manner:
DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern)
But I need to convert data for all the rows in my DataSet to string. Does anyone have an idea on how I can achieve this?
Thanks.

When you get the DataSet:
locate apropriate DataTable
add new DataColumn
in one loop you populate new Column with (your DateTime).ToString()

Get the Dataset.
for each row convert to string and
put it in new dataset (along with
rest of data).

I don't think it's possible to change a column type after the table been filled. I think you should create a second table on your dataset and copy the information you need transforming the date in the process.

New answer :)
I have been googling an came up with this site: Linq to Dataset
That example shows how you can use linq on a dataset, I am guessing that you could use a query to perform the data transformation and place it on the new datatable. Not sure if it will perform better then the loop

If I were you, I would keep the data in the DataTable as it is. It is after all, meaningful data that would lose its meaning upon conversion. I would make any desired modifications only when displaying/rendering the data because that implicitly requires a conversion of the data into strings (with optional formatting).
Any DateTime variable can be rendered as a string (with culture-sensitive formatting) using the simple code:
DateTime.Now.ToShortDateString();
// Or
DateTime.Now.ToString("d");
This function already uses formatting information derived from the current culture.
I really would suggest that you take another look at your scenario to evaluate if you really need to change the datatype of data in the dataset itself. (or provide us with more information)

Related

Is there a way to display dynamic columns in Oracle apex

Long story short, I can't use pivot for this task due to the long elements that I need to include in the columns. Although I tried to create a Classic Report based on function in Oracle Apex. The query it's generated correctly but it's not working in the Classic Report.
A general hint first: Output your variable l_sql to your console using dbms_output.put_line or use some kind of debugging table where you can insert it into. Also be careful about the data type of that variable. If you need to expand the SQL you can reach a point where you need to use a CLOB variable instead of varchar2.
You will need to supply table structures and test data if you like to have your problem analyzed completely, therefore I will at first give you some general explanations:
Use Generic Column Names is ok if you have a permanent, unchangable amount of columns. But if the order of your columns or even the amount can change, then this is a bad idea, as your page will show an error if your query results in more columns than Generic Column Count
Option 1: Use column aliases in your query
Enhance your PL/SQL Function Body returning SQL Query in a way that it outputs verbose display names, like this:
return 'select 1 as "Your verbose column name", 2 as "Column #2", 3 as "Column #3" from dual';
That looks like this:
It has the disadvantage that the column names also appear in this way in the designer and APEX will only update these column names if you re-validate the function. You will have a hard time to reference a column with the internal name of Your verbose column name in a process code or dynamic action.
However it still works, even if you change the column names without telling APEX, for example by externalizing the PL/SQL Function Body into a real function.
Option 2: Use custom column headings
A little bit hidden, but there is also the option of completely custom column headings. It is almost at the end of the attributes page of your report region.
Here you can also supply a function that returns your column names. Be careful that this function is not supposed to return an SQL query that itself returns column names, but instead return column names seperated by a colon.
With this method, it is easier to identify and reference your columns in the designer:
Option 3: Both of it
Turn off Generic Column Names, let your query return column names that can be easily identified and referenced, and use the custom column headings function return verbose names for your users.
My personal opinion
Im using the 3rd option in a production application where people can change the amount and order of columns using shuttle items on the report page themselves. It took some time, but now it works like a charm, like some dynamic PIVOT without PIVOT.

Issue with simple sorting. Should I fix at database or in code?

I am working on a sort function for a table column that holds desk numbers and names.
This is a legacy program and was designed so that this column is nvarchar.
Because of this, the sort function cannot sort numerically as shown below:
Should I go into the database and alter this column to add leading zeros to number-only entries? Is this even do-able since the column is nvarchar?
Or should I add code at the object-level to add leading zeros just before the data is presented?
I would add one getter property in my class so it look like
public int Ordering
{
get
{
return int.Parse(CharColumn);
}
}
and when getting list of those objects simply order by that new property.
SQL Server is built upon SET Theory which states that, if you order your result set, you get non-relational data.
I would create another database column with the numeric value (there may be some columns that don't convert well, make sure you identify these and work to convert them). Then I would work to convert your application to use the new values. If the conversion is too great you could make sure all new development uses the new column and old code is migrated the next time someone touches it.
The risk to your approach is too fold, storing them in varchar is inefficient with both memory and processing power. Adding zeroes will help with the sorting but not fix the root issue.
Here is another question that I think will help you: SQL Server : error converting data type varchar to numeric

DataColumn.Expression RowFilter on Dataview

Maybe this is stupid question or maybe I have designed my code completely wrong but anyhow, here is my question...
I have a "dynamic" sql-query where its impossible to take all the parameters i need for making the query parameterized, therefore i get my data and put it in a dataview and after that i search for the rows I want to show in the dataview.
One of the columns are a column named id. Id is primary key and auto_increment in the table and therefore it's an int.
Now to my question, i want to present all my matching id with the number the user put in my textbox. Let us say my id consist of 5 numbers and the user put the 4 first, then in the perfect world i would have 10 matches (12340-12349 as an example). Doing this on a string is very easy using RowFilter and the operator LIKE combined with a wildcard. But how can i do something similar on integers? Do i have to convert it to strings and wont that ruin the rowfilter expression?
Not a live or death-situation... im more curious if the ice im walking is very thin... :)
Rowfilter expression supports CONVERT function, so technically you can convert your integer ID to string to do the LIKE command:
MyDataView.RowFilter = "Convert(ID, 'System.String') LIKE '1234*'";
But do try to offload the filtering to backend. It's unlikely that you have unlimited number of parameters and SQL is very flexible in allowing you different combinations.

ASP.net: Efficient ways to convert DataSets to GenericCollection (Of ObjectType)

I currently have a function that gets some data from the database and puts it into a dataset. The return type on my function is GenericCollection (Of CustomerDetails)
If I do this:
Dim dataset As DataSet = Read(strSQL.ToString) 'Gets Data from DB
What's the most efficient way to map the dataset results to an collection of objects. More importantly, since I'm using GenericCollection, is there a way to do this in which I can call a function from the ObjectType class (CustomerDetails) that would have a means to converting that specific object.
Or is there a way in which I can use a function that would handle all types?
Is there a way to do something like:
Return returnedResults.TransformDataSet(dataset)
In which returnedResults is an object collection Of CustomerDetails, or would it simply be easier to have TransformDataSet return an object collection Of CustomerDetails by itself?
Thanks for any help.
Do you plan to generate the dataset, create your collection, then throw away the dataset? If so, I would suggest dispensing with the dataset completely, and use a data reader (SqlDataReader if you are using sql server). You can iterate through the reader and create your collection as you go.
The dataset is a heavy, xml-based gadget that is great if you need to keep it around and use it for other stuff, but if you are just going to use it as a temporary intermediate data store between the db and you collection, then I would lose it.

Format columns for ASP.Net GridView based on data type

I have a very simple ASP.Net page that acts as a front end for a stored procedure. It just runs the procedure and shows the output using a gridview control: less than 40 lines of total code, including aspx markup. The stored procedure itself is very... volatile. It's used for a number of purposes and the output format changes regularly.
The whole thing works great, because the gridview control doesn't really need to care what columns the stored procedure returns: it just shows them on the page, which is exactly what I want.
However, the database this runs against has a number of datetime columns all over the place where the time portion isn't really important- it's always zeroed out. What I would like to be able to do is control the formatting of just the datetime columns in the gridview, without ever knowing precisely which columns those will be. Any time a column in the results has a datetime type, just apply a given format string that will trim off the time component.
I know I could convert to a varchar at the database, but I'd really don't want to have to make developers care about formatting in the query and this belongs at the presentation level anyway. Any other ideas?
Finally got this working in an acceptable (or at least improved) way using this code:
Protected Sub OnRowDatabound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim d As DateTime
For Each cell As TableCell In e.Row.Cells
If Date.TryParse(cell.Text, d) AndAlso d.TimeOfDay.Ticks = 0 Then
cell.Text = d.ToShortDateString()
End If
Next cell
End If
End Sub
If you are auto generating the columns which it sounds like you are. The procedure for using the grids formatting is awful.
You would need to loop through all the columns of the grid, probably in the databound event and apply a formatting expression to any column you find is a date column.
If you are not auto generating and you are hadcoding columns in your grid you will also know alreayd which columns are date columns and you can apply the same format expression to that column. It's something like {0:ddMMyyyy} but you will have to look it up as that's probably not quite right.
so to summarise hook into the databound event. loop through the column collection and ascertain if the column is a date column. I wonder how you might do this :). If you decide a column is a date column set its format expression.
Voila
---------------------- EDIT
Ok how about you write you method that returns the data from the proc to return a datatable. You can bind the datatable to your grid after formatting the data in the datatable. The datatable.Columns collection is a colection of DataColumns and these have a DataType property. You may be looking for System.DateTime or DateTime and it may be one of the properties of the DataType property itself :). I know it's cumbersome but what you are asking is definitly going to be cumbersome. Once you've identified date columns you may be able to do something with it.
If not i'd start looking at the data readers and see if there's anything you can do there or with data adapters. I wish I could give you a proper answer but i think however you manage to do it, it's not going to be pretty. Sorry
if using explicit bound columns is an option, add a DataFormatString to your boundField
<asp:BoundField DataField="Whatever" ... DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="False"/ >
otherwise you could look at doing the formatting the GridView.OnRowDataBound event
You can use the isDate() function to see if something is a valid date and then use dateformatting options to make it look like you want.
Some examples for date formating:
http://datawebcontrols.com/faqs/CustomizingAppearance/FormatDateTimeData.shtml

Resources