In the application I am working on, I have a TableAdapter, and a RadGridView (Telerik control - their version of the DataGridView). The TA is pulling different elements from our database, including PhoneNumber, which is stored as varchar.
In my GridView, I would like to display this format as (123) 456-7890. Unfortunately, I have been unable to accomplish this.
I have tried the following (which is Telerik's recommended method):
radGvUsers.Columns["PhoneNumber"].FormatString = "{0: (###) ###-####}";
This results in the value displaying as it does in the db: 1234567890
I know (ok, I think) this is because it is stored as varchar and needs to be converted to a number, but I don't know how or where (i.e. at the TA or GridView level) best to do this.
Any suggestions? Feel free to ask more questions if I did not supply enough info!
You can convert the string to a numeric in the SQL Statement
Select Convert(bigint, PhoneNumber) AS PhoneNumber FROM sometable
You can easily do like below. No need to get data as string from database.
radGvUsers.Columns["PhoneNumber"].DefaultCellStyle.Format = "(###) ###-####";
Related
I have a package. It has a query that feeds into a Script Component.
In the query I am selecting a varchar(8) column from a table and then I CAST(myDateCol AS varchar(10)).
SELECT
myPK,
CAST(myDateCol AS varchar(10)), --myDateCol defined as varchar(8)
myOtherCol
FROM
MyServer.MySchema.MyTable
In my script, I am trying to add two characters to the Row.myDateCol in Input0 but I get a Buffer Error and it is in the property setter for myDateCol. You can see that it sets the property to 8 characters but errors out after that.
What I've done is add an output column with Length = 10, set it, and mapped that to the next component in the package but that seems a little silly.
Is there a way to force the size of your input columns based off of the query OR is there a way that I can manually force a refresh in case the package is just stuck thinking that I'm dealing with a varchar(8) as the CAST operation was added later?
Additional Info:
Row.myDateCol = "20170404"
Row.myDateCol = "2017-04-04" // Errors out
This is normal behavior for SSIS. When you create a data source which uses a SQL query, SSIS will look at your query and build the the metadata for the dataflow. The data source will only recalculate that metadata if you change the structure of your query, for example number columns or their names.
The easiest way to force a refresh of the data types without resorting to renaming columns is to go to the columns page of the data source editor, Untick and then tick the top tick box of the Available External Columns. This will deselect all columns and re-select them and at the same time refresh the metadata. You can easily confirm this by hovering your mouse over the External\Output column names listed in the lower section.
Your problem is the result of dealing with Date(Time) as text instead of the number(s) it is. And I really cannot tell from your question if you want to want to add the extra characters added in at the Data Layer (Sql) or at the Application (C#) Layer.
Casting VarChar(8) => VarChar(10) will still just return VarChar(8) if you don't fill in (pad) that value. You could try a Cast VarChar(8) to Char(10).
Another option would be a double conversion of your column value to Date and then back to your desired varchar(10).
SELECT myPK,
Convert(VarChar(10), Convert(Date, myDateCol, 112), 120),
myOtherCol
FROM
MyServer.MySchema.MyTable
So, after some playing around, I found that renaming the column changed the size to varchar(10) per below:
SELECT
myPK,
CAST(myDateCol AS varchar(10)) AS DATECOL,
myOtherCol
FROM
MyServer.MySchema.MyTable
I then changed it back
SELECT
myPK,
CAST(myDateCol AS varchar(10)),
myOtherCol
FROM
MyServer.MySchema.MyTable
And the change stuck. I don't know why or how but VS/SSIS somehow never refreshed itself to change to a different type. I assume it has no handling for query changes after the initial query is input unless names/aliases change.
This wasn't just my machine either. Weird.
I have a database table like this on SQL Server:
USER PASSWORD
1 samplepassword
2 NULL
3 NULL
4 sample_password
I want to replace the NULL values in the PASSWORD column, along with other columns, with values like '(Not set)' or '-' upon displaying it to the user in a DataGridView.
There are three ways I know of in achieving this. First is to use the NullValue property of the column's DefaultCellStyle. The concern with this method is that the designer would create multiple copies of the same DefaultCellStyle - one per column.
Then there's the CellFormatting event of the DataGridView. Lastly, the replacing can be done on the SQL statement itself, ala ISNULL(password, '(Not set)').
Considering that this DataGridView can be filtered afterwards by the user (e.g. show only those without a password), what is the more suggested way in doing this?
Thanks!
Formatting is not SQL server responsibility, keep formatting in your UI code.
Use DefaultCellStyle and create instance of DefaultCellStyle in the code and set same instance to the all columns of datagridview manually.
Or assign only NullValue property to already existed styles
const string NULL_VALUE = "not set";
DataGridView.Columns["ColumnName1"].DefaultCellStyle.NullValue = NULL_VALUE;
DataGridView.Columns["ColumnName2"].DefaultCellStyle.NullValue = NULL_VALUE;
Not 100% sure on SQL Server but on MySQL I wold do the following
SELECT USER, IF(PASSWORD IS NULL,'Not Set', PASSWORD) AS PASSWORD FROM TABLE
SELECT ISNULL(YourColumn, 'yourcharacter' ) FROM YourTableName
Run a JavaScript or jQuery function after your DataGridView load, to find empty values from DataGridView and replace it with "(Not set)" or "-".
OR
Update your dataset values which are empty with values "-".
The selected answer is the best one from a paradigm standpoint, though you can also handle this by creating a helper function to handle nulls. This will make your default values something you can change based on your datatype. It also lets you manage nulls before they ever touch the UI, but without affecting your queries, which is essential if you have to handle mathematics before displaying output.
public static dynamic NullCheck(object d, dynamic default)
{
return DbNull.Value == d ? default : d;
}
Just be ready to cast the result as needed in your code, such as ((foo)(Nullcheck(foo, bar))).
I retrieve value from database like this 173557.0000. I want to display like 1,73,557.00.
This is my code what tried
Table1001Hour.Rows[i].Cells[0].Text = rd["hour"].ToString();
Table1001Hour.Rows[i].Cells[1].Text = string.Format("{0:C}", Convert.ToInt32(rd["salesCost"].ToString()));
But it throws an error message.
Input string was not in a correct format.
If I don't convert to string it shows like same as it is 173557.0000
Thanks
It looks like the problem is here:
Convert.ToInt32(rd["salesCost"].ToString())
So... don't do that? The data coming back from the database is probably just an int, so: (int)rd["salesCost"] (or, if you're unsure of the specific type, Convert.ToInt32(rd["salesCost"])) should be fine. You could also then use the overload ToString; giving you:
Table1001Hour.Rows[i].Cells[1].Text = ((int)rd["salesCost"]).ToString("C");
(although based on the .0000, it could be decimal or double - the latter of which would be a very bad choice for financial data)
To be honest, I think it is a mistake to have UI code and DB code touching each-other directly, but that might just be me. If it were me, I'd be populating an object model from the database, and separately writing the object model to the UI.
I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.
I have a grid that is populated using an Oracle 11g query that returns a TIMESTAMP(6) WITH TIME ZONE field along with other fields.
When I select a date range for data to be displayed that goes from 12/26/2014 to 1/5/2015, and then try to sort by this column (asc or desc), it does not sort properly. For example, in desc order it displays from 01/01 to 01/05 and then from 12/26 to 12/31. Looks like string sorting.
I am guessing a TIMESTAMP(6) WITH TIME ZONE field that contains a value like 21-JAN-2015 18:17:16:00000 USA/EASTERN is not recognized as a date-time but rather a string. Is there any way to resolve this issue?
Turning a comment into an answer:
There is a number of options:
(i) Rely on the database to sort the data correctly - which you might want to prevent for performance reasons.
(ii) Instruct the grid to handle the timestamp column as such (and not as a string column) - which might not be possible.
(iia) Use a different grid component, which handles date columns properly.
(iii) Use a hidden (string) column with the timestamp formatted as 'YYYY-MM-DD HH24…' for sorting.
(iv) Write your own sort routine.
Feel free to provide more detail if and as you see fit.