I'm trying to add zeros in front of datatable column values if the lenght is less than 6 digits.
Ex: I have a column "SRNumber" in datatable with values 123, 2345, 56, 34523 etc and Would like to have my results like this 000123, 002345, 000056, 034523.
Note: I would like the manipulate the data in Datatable not in the sql query which retrieves the data. I have seen the solutions where we can add leading zeros to a string or variable but in mycase would like to do it for all the values in datatable columns.
ok, i figured it out with help of #eddie_cat answers. Here is what i did.
foreach (DataRow row in table.Rows)
{
row["SRNumber"] = row["SRNumber"].ToString().PadLeft(6, '0');
}
table.AcceptChanges();
Here, "SRNumber" is the column name in which i'm adding leading zero's. I hope this helps someone.
as eddie_cat said,
loop through the values and update the required fields
foreach(DataRow dr in mydatatable)
{
dr[myfield] = String.Format("{0:0000}", int.parse(dr[myfield]))
}
Note that you should first convert your string to int.
the example I've used int.parse(...) might throw an exception if dr[myfield] is dbnull.
I am not sure if you are looking for a SQL solution or a C# solution so I'll provide SQL since other have given you the C# solution:
UPDATE MYTABLE
SET SRNumber = RIGHT('000000' + SRNumber,6)
WHERE len(SRNumber) < 6
Related
I want to add my dtbl data table record into my DtCloned data table, but after changing the type of column index 2 then fill it into dtCloned, I have an issue filling my record to dtcloned after changing the types.
DataTable dtCloned = dtbl.Clone();
dtCloned.Columns[2].DataType = typeof(TimeSpan);
for (int i = 1; i <= dtbl.Rows.Count; i++)
{
DataRow row = dtCloned.NewRow();
for (int j = 0; j < dtbl.Columns.Count; j++)
{
DataColumn dtc = new DataColumn();
if (j == 2)
{
//dtc.DataType = System.Type.GetType("System.Datetime");
//dtCloned.Columns.Add(dtc);
string s = dtbl.Rows[i][dtbl.Columns[j]].ToString();//12/31/1899 10:00:00 AM Tables[2].Rows[j][Model.Tables[2].Columns[i]]
string FTime;
FTime = s.Substring(11);
DateTime dt1 = Convert.ToDateTime(FTime.ToString());
string FTime2 = dt1.ToString("HH:mm:ss tt");
DateTime dt = DateTime.ParseExact(FTime2, "HH:mm:ss tt", null, DateTimeStyles.None);
string FTT = dt.ToString("HH:mm:ss");
row[i] = FTT;//DateTime.ParseExact(FTime, "HH:mm:ss tt", CultureInfo.InvariantCulture);
}
else
row[i] = dtbl.Rows[i][dtbl.Columns[j]];
}
dtCloned.ImportRow(row);
}
Have you considered just adding a new column to the dataTable pulled locally of the destination type expected, then do foreach() of every row and update the one column you wanted added.
dtbl.Columns.Add("YourTimeSpan", typeof(timespan));
foreach( DataRow dr in dtbl.Rows )
{
dr["YourTimeSpan"] = WhateverYouAreTryingToDo;
// the bulk of code that does all your date / tryparse conversion stuff.
}
So first, add the column of a time-stamp data type. Leaves original table alone so you dont have to duplicate everything. Now, by cycling through each DataRow in the DataTable, you have the row object.
By referencing the dr["YourTimeSpan"], you are referring to the column by its column name instead of ordinal representation. For your original data, if you know that column name you could refer to it that way too such as dr["OriginalDateTimeColumn"], but you could still do via dr[2] if you wanted to keep the 0-based ordinal column reference.
Now I am not sure what you are really doing. Trying to convert a string to a date/time based on known format? But if the original value of the cell IS a date/time, you should be able to work directly from it AS a datetime field and apply its normal .ToString() formatting options.
If you can EDIT YOUR EXISTING question with details of the original column data types, (string vs datetime), then you dont need to do conversions. If the originating data is coming from some SQL database, and the original data type is of a date/time or timestamp type of column, I would suggest adding the formatted value you want directly from the SQL engine vs you trying to keep parsing it here.
FEEDBACK
So, your existing table, column #3 (ordinal column 2 when zero-based) IS a date/time column. And you are just trying to convert it to a single string in 24-hr clock format? So 3:27pm = 15:27 via 24-hr clock?
Here is a sample of checking/confirming data type you are working with. I just put a breakpoint in the program when it got to my table and columns in-place and I added a blank row. So add to the watch window your "dtbl.Columns[2]" and expand it. Check to see/confirm if your column's data type is already that of DateTime structure. If so you don't need to do conversions.
If the value for the data type IS DateTime, and you only care about the string representation of it as 24hr, simple enough via the loop I has above, but instead, you would just add a column of a STRING data type, not timespan.
Then you could do
if( dr[2] is System.DBNull )
// no such value in the row date/time column
dr["YourTimeSpan"] = "";
else
// there IS a datetime value to work with.
// "HH" upper case is specifically 24-hr clock, then minute and second
dr["YourTimeSpan"] = dr[2].ToString("HH:mm:ss");
Note, that by this measure, it will have your extra column to the LAST column on the data row, but still simpler to work with than full cloning and doing crazy parse testing. Please let me know if helps and if you have any other issues.
If string is the final data type, just make sure you add the column as
dtbl.Columns.Add("YourTimeSpan", typeof(string));
instead of typeof(timespan) in the original example.
I'm having a problem when I insert a value it will show a error:
incorrect integer value: "for column 'taxi_id' at row 1
string
insertcmd = "INSERT INTO taxi(taxi_id) VALUES ('#taxi_id')";
myCmd.Parameters.AddWithValue("#taxi_id", BigInteger.Parse(merchantId,NumberStyles.Integer));
taxi_id in database is of type Bigint(255).
Can anyone help?
Since you are using quotes around #taxi_id, it is considered a literal textual value and not a parameter.
Remove the quotes so #taxi_id becomes a parameter:
INSERT INTO taxi(taxi_id) VALUES (#taxi_id)
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.
DataRow drEmpty = dsResult.Tables[1].NewRow();
dsResult.Tables[1].Rows.InsertAt(drEmpty, 0);
DataRow drBranch = dsResult.Tables[1].Rows[1];
drBranch[1] = "Branch"; <--error
dsResult.Tables[1].Rows.InsertAt(drBranch, 1);
my expected output for this few line of code is to add first empty row data into my dropdownlistbox and second row by adding "Branch" into the it but i failed to do so
Error msg given --
Input string was not in a correct format.Couldn't store in ows_ID Column. Expected type is Int64.
after that i try to change to
drBranch[1] = int64.Parse("Branch");
and i get another error
second error msg -- Input string was not in a correct format.
i get the answer that i want already, i will post the answer after 7 hours ,thanks all
In you example drBranch[1] represents the ows_ID column, which only accepts values of type integer. That means only numbers without a decimal point are allowed.
You could convert strings that contain numbers like "55" to an integer using Int64.Parse("55"), but you can't convert strings like "Branch" to integer. You're trying to store a string in the ows_ID column. Maybe you're trying to access the wrong index?
The problem is that "Branch" is not integer.
To cast a value into integer you need an integer value as a string like "526", "100".
I assume you think that the column ordinal is one-based but it's zero-based, hence drBranch[1] is the second column.
In my opinion it's better to use the column's name instead:
drBranch.SetField<String>("Branch", newBranch);
(i'm using the SetField extension method since it's strongly typed and supports nullables)
I would suggest using a DataTable before using DataRow:
DataTabel dtResult = dsResult.Tables[1].Clone();
dtResult.Columns[1].DataType = Type.GetType("System.String");
DataRow drEmpty = dtResult.NewRow();
dsResult.Tables[1].Rows.InsertAt(drEmpty, 0);
DataRow drBranch = dsResult.Tables[1].Rows[1];
drBranch[1] = "Branch";
dsResult.Tables[1].Rows.InsertAt(drBranch, 1);
I have a string "-4.00 %" which I need to convert to a decimal so that I can declare it as a variable and use it later. The string itself is found in string[] rows. My code is as follows:
foreach (string[] row in rows)
{
string row1 = row[0].ToString();
Match rownum = Regex.Match(row1.ToString(), #"\-?\d+\.+?\d+[^%]");
string act = Convert.ToString(rownum); //wouldn't convert match to decimal
decimal actual = Convert.ToDecimal(act);
textBox1.Text = (actual.ToString());
}
This results in "Input string was not in a correct format." Any ideas?
Thanks.
I see two things happening here that could contribute.
You are treating the Regex Match as though you expect it to be a string, but what a Match retrieves is a MatchGroup.
Rather than converting rownum to a string, you need to lookat rownum.Groups[0].
Secondly, you have no parenthesised match to capture. #"(\-?\d+\.+?\d+)%" will create a capture group from the whole lot. This may not matter, I don't know how C# behaves in this circumstance exactly, but if you start stretching your regexes you will want to use bracketed capture groups so you might as well start as you want to go on.
Here's a modified version of your code that changes the regex to use a capturing group and explicitly look for a %. As a consequence, this also simplifies the parsing to decimal (no longer need an intermediary string):
EDIT : check rownum.Success as per executor's suggestion in comments
string[] rows = new [] {"abc -4.01%", "def 6.45%", "monkey" };
foreach (string row in rows)
{
//regex captures number but not %
Match rownum = Regex.Match(row.ToString(), #"(\-?\d+\.+?\d+)%");
//check for match
if(!rownum.Success) continue;
//get value of first (and only) capture
string capture = rownum.Groups[1].Value;
//convert to decimal
decimal actual = decimal.Parse(capture);
//TODO: do something with actual
}
If you're going to use the Match class to handle this, then you have to access the Match.Groups property to get the collection of matches. This class assumes that more than one occurrence appears. If you can guarantee that you'll always get 1 and only 1 you could get it with:
string act = rownum.Groups[0];
Otherwise you'll need to parse through it as in the MSDN documentation.