how to store number in double digit format? - c#

I have 100 textboxes in 00 to 99 manners in form. I want to store first 0 to 9 in double digit format like 00, 01, 02, .... 09. How can i store it in sql database in that format without making it a string. I am doing project in c#.

If you need to have those values in that format just in your table;
You need to run a query to insert a new row or update a valid row;
string query = string.format("Insert Into <table name> Values (list of values)", int value(s));
or
string query = string.format("UPDATE <table name> Set (list of '<field name> = <value>'s)", int value(s));
You need just use {0:00} instead of {0} in your query string.
If you use sqlCommand at setting parameters use it in this way = string("{0:00}", int value)
Note: all codes are sample, you need to generate your own codes.
If you need to store your value with format you should use one of char data-types in your table.

If your filed is "int", I think it will be not possible. As 09 is 9 in integer. As per thumb rule of integer the leading ZERO have no value.
But you can always SELECT with formatting OR else use "varchar" type to store it as you need.
Hope I am clear enough..!!

Related

Format String to Match Specific Pattern

I am trying to figure out how to format a string to a specific pattern.
When a user is entering their employee id number, they often get confused on what is expected from them. Because they are often told that their employee id is either a 5 digit or 4 digit number depending on when they were hired.
For example, my employee id number is E004033 but for most of our systems, I just have to enter 4033 and the system will find me.
We are trying to add this to one of our custom pages. Basically what I want to do is format a string to always look like E0XXXXX
So if they enter 4033 the script will convert it to E004033, if they enter something like 0851 it will convert it to E000851 or if they enter 11027 it will convert it to E011027
Is there a way basically add padding zeros and a leading E if they are missing from the users input?
You can simply:
var formattedId = "E" + id.PadLeft(6, '0');
To remove an existing leading E(s)
var text = "E" + val.TrimStart(new[] {'E'}).PadLeft(6, '0');
Make sure the user's input is an integer, then format to 6 spaces using String.Format.
int parsedId;
bool ok = int.TryParse(id, out parsedId);
if (ok)
{
return String.Format("E{0:000000}", parsedId);
}

Input string was not in a correct format. C# error SQL database

I have a very BIG PROBLEM.
I want to delete a row from my database sql in C#.
here is my code:
int x = Convert.ToInt32(dataGridView1.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.CommandText = "delete from Table2 where Name=#N";
cmd.Parameters.AddWithValue("#N", x);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
and finally im get a problem
Input string was not in a correct format.
Help me.
I get the error in first Line.
First problem:
dataGridView1.SelectedCells[0].Value is not a valid integer value, so Convert.ToInt32 fails.
Did you mean
string x = dataGridView1.SelectedCells[0].Value;
instead?
Second problem:
You are comparing the Name field to an integer value. I'm assuming Name is a _string_ value in the database (otherwise it's poorly named). When SQL looks for matching values, it will try to convert every value ofNamein the database to a number. if ANY value in theName` field is not a valid number, the query will fail.
I've read that null or empty string will return 0 (to be confirmed)
Here my guess :
Depending of your country, numbers should be wrote :
1.234
or
1,234
Solution
Hugly solution : You can simply do a :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value.Replace(".",","));
Good solution : Or use Convert.ToInt32(String, IFormatProvider) :
Convert.ToInt32(dataGridView1.SelectedCells[0].Value,CultureInfo.CurrentCulture)
EDIT -1 without comment, i'm please to help.

Recognise a leading 0 in an int?

I am trying to insert an entry into a database:
mySqlCommand.CommandText = "INSERT INTO table_name (col1, col2) values (#number, #word);";
mySqlCommand.Parameters.Add("#number", MySqlDbType.Int32);
mySqlCommand.Parameters.Add("#word", MySqlDbType.VarChar);
mySqlCommand.Parameters["#number"].Value = 0110;
mySqlCommand.Parameters["#word"].Value = "Hello";
However when I get it back out, it's stored as 110 instead of 0110. How can I get it to recognise the leading 0?
Well your datatype is integer. when 0110 is cast to integer it becomes 110.
To achieve your goal you need to set its datatype as varchar both in table and
MySqlDbType.Int32 to MySqlDbType.VarChar.
Hope this will help you.
There is nothing like leading 0 in int. however if u want to store the leading 0 then you can convert data type of that field to Varchar..
or by programmatically you can also pad 0 in any variable but again it will be converted to string.
Like this
int Anynumber= 5;
string AnynumberWithZero = string.Format("{0}", Anynumber.ToString().PadLeft(2, '0'));
Result will be"05"

How to split my String into 3 delimited Strings (regardless of SubString Length)?

I'm storing strings in an array. An example would be:
ssnDateTime = "123456789|20140225|114528"
I was attempting to store each substring into it's own variable for use, like the below:
string SSN = ssnDateTime.Substring(0, 9);
string Date = ssnDateTime.Substring(ssnDateTime.Length - 15, 8);
string Time = ssnDateTime.Substring(19);
This worked fine for 5 of my 10 test records, but the 6th has a time value of 91514, leading to my 3 strings being:
SSN = 123456789
Date = |2014022
Time = 91514
When my application attempts to run INSERT INTO Library.TrackingTable (SSN, DATE, TIME) VALUES ("123456789", "|2014021", "91514"), The AS400 naturally complains about the | in the Date value.
What is a way I can get each of the SSN, Date, and Time values out of my main string with the delimiters, regardless of the substring length (to prevent the mentioned issue when time is a shorter value than 6 characters)?
SSN will naturally be consistently 9 characters, and Date will be in the 8 character format of 20140225, but Time can be either the 5 or 6 characters depending on value.
Seems to be a perfect fit for string.Split
ssnDateTime = "123456789|20140225|114528"
string[] subs = ssnDateTime.Split('|');
string SSN = subs[0];
string Date = subs[1];
string Time = subs[2];
string.Split returns an array of strings splitting the orginal string at the separator passed as argument.
Of course this code doesn't check if the resulting string array contains really three elements, in a production environment a check like
if(subs.Length > 0
date = subs[1];
if(subs.Length > 1)
Time = subs[2];
should be mandatory....
string[] parts = "123456789|20140225|114528".Split('|');
http://www.dotnetperls.com/split

How to retrieve 0 as the first number in C#

scenario:
I have a database having a record 001234 and I am calling it with cmd.executescaler(); into a int variable. The problem is when I retrieve the saved data (001234) data from that variable it gives only 1234. 00 in 001234 are important, this was the problem first coming in db where sql omits the first zero's then I changed the datatype to nvarchar which works, how I can retrieve the data on the form exactly 001234.
Note: I cannot take the data into string as I have to also apply some calculations on them.
using Sql Server visual studio 2010 c#
Hope it is clear not vague. If you need more information tell me.
Thanks in advance.
Numeric datatype don't have and can't have leading zeros. So the only way to have leading zeros is to store the value as a string.
However, this is just a matter of formatting the output that is shown to the user. You can read the database value into an int variable, do your calculations and when showing the value, you can do:
string displayValue = String.Format("{0:D6}", intValue);
and show the value of displayValue.
If you want to work on the Code side:
string displayValue = String.Format("{0:D6}", intValue);
If you want to work on the DB side you need a Pad function that allows to write this kind of query:
SELECT dbo.PadString ('8', '0', 5)
->Result: 00008
SELECT dbo.PadString ('abc', '*', 12)
->Result: *********abc
SELECT dbo.PadString ('abc', '0', 7)
->Result: 0000abc
Create a function in T-SQL
CREATE FUNCTION [dbo].[PadString]
(#Seq varchar(16),
#PadWith char(1),
#PadLength int
)
RETURNS varchar(16) AS
BEGIN
declare #curSeq varchar(16)
SELECT #curSeq = ISNULL(REPLICATE(#PadWith, #PadLength - len(ISNULL(#Seq ,0))), '') + #Seq
RETURN #curSeq
END
If those leading zeros have some meaning and can't be left out, conversion can be done:
int number = 0;
string strNumber = (string)cmd.ExecuteScalar();
if(int.TryParse(strNumber, out number))
{
// process number
// if you want some output to be formatted with leading
// zeros you can use PadLeft method
int totalNumberOfDigits = 6;
string strResult = number.ToString().PadLeft(totalNumberOfDigits, '0');
}
you can use string.PadLeft() in c# after retrieving your number, as you have fixed length numbers
example from msdn,
string str = "forty-two";
char pad = '.';
Console.WriteLine(str.PadLeft(15, pad)); // Displays "......forty-two".
Console.WriteLine(str.PadLeft(2, pad)); // Displays "forty-two".
The reason SQL does this is because 001234 = 1234 in any number format no matter what type it is. As a "Dirty" solution you could cast it as an int which will give you 1234, perform your calculations and then cast your answer back to string adding the leading zeros.
int myValue = Int32.Parse("001234");
int myAnswer = myValue * 2;
string myAnswerString = "00" + myAnswer.ToString();
The best way to go though would be to format your string as suggested by #Thorsten Dittmar. If possible, do not store numeric values in the database as varchar to begin with, however I know that this is sometimes a requirement, but the I cannot see the point on doing calculations on those values.

Categories