I searched all webs and didn't find any solution for my problem. I am new to c# and stack overflow community but am really stuck in this issue.
I have a button to add date and time separately into a datagridview. While filling the rows i am saving row values in SQL Server but its giving exception Failed to convert parameter value from a Int32 to a DateTime when i send it database.data type in c# and SQL Server is Datetime
Here's the code of adding date and time to datagridview
private void addDateTime2_Click(object sender, EventArgs e)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = dateTimePicker9.Value.ToString("dd-MM-yyyy");
dataGridView2.Rows[n].Cells[1].Value = dateTimePicker7.Value.ToString("HH:mm:ss");
}
Here's the code that i insert to database:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
string StrQuery = "INSERT INTO [dbo].[callRedirect] (ISFsectionId, callRedirectDate, incidentNo, callRedirectTime, callRedirectGrade, callRedirectFName, callRedirectLName, callRedirectSerialNo, callRedirectRemark) VALUES (#ISFsectionId, #callRedirectDate, #incidentNo, #callRedirectTime, '"
+ dataGridView2.Rows[i].Cells["Column12"].Tag + "', '" + dataGridView2.Rows[i].Cells["Column13"].Value + "', '" + dataGridView2.Rows[i].Cells["Column14"].Value + "', '" + dataGridView2.Rows[i].Cells["Column20"].Value + "', '" + dataGridView2.Rows[i].Cells["Column19"].Value + "')";
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = StrQuery;
cmd.Parameters.AddWithValue("#incidentNo", textBox4.Text);
cmd.Parameters.AddWithValue("#callRedirectDate", dataGridView2.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#callRedirectTime", dataGridView2.Rows[i].Cells[1].Value);
cmd.Parameters.Add("#ISFsectionId", SqlDbType.DateTime).Value = dataGridView2.Rows[i].Cells["Column11"].Tag;
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
}
The only line that could throw this error is
cmd.Parameters.Add("#ISFsectionId", SqlDbType.DateTime).Value =
dataGridView2.Rows[i].Cells["Column11"].Tag;
I seriously doubt that your ISFsectionId is a datetime. I'm also going to bet that Tag contains an integer.
Also note that your grid contains string values instead of DateTimes. This means that either you use string fields of actual date and time, or that ADO.NET is accidentally able to parse your strings to the underlying type. I say accidentally, because this could break if the code run on a locale with different formatting.
To avoid conversion issues, use date and time types in the database and don't convert them to string when loading them and binding them to the grid. Use the DataGridViewStyle.Format property of each column to specify how you want it to be displayed
Related
This is my C# code - I am running the query
INSERT INTO PM
VALUES ('Ali', '6777777', '3', 'Batsman', 'Fine Player', 'njhuh8obj', 'Lahore');
It is running fine in the database, but not this.
protected void btnAdd_Click(object sender, EventArgs e)//button that add players
{
// for picture to be uploaded
string path = "~/Admin/Players" FileUploadPicture.FileName;
FileUploadPicture.SaveAs(Server.MapPath(path));
SqlCommand cmd = new SqlCommand("INSERT INTO PM VALUES ( '" + TxtPlayerName.Text + "','"+TxtPlayerType.Text + "','" + TxtPlayerBasePrice.Text + "','" + TxtPlayerRecord.Text + "',
'" + ddlCat.SelectedItem.Value + "','" + path + "','" + TxtPlayerAddress.Text + "')", con);//Query of my C# page
// open connection with database
con.Open();
// Command for running query
cmd.ExecuteNonQuery();
con.Close();
// message shown after player is added
Response.Write("<script>alert('**Player Added**')</script>");
}
It seems that there is a problem in code of my C# page not in database, but I am not sure about that.
So please help me to solve this out...
It looks like the second column of your database table accepts an integer value but you are passing a string (TxtPlayerType.Text). If you want to insert an entry with only values for select columns you must specify the column names as follows:
INSERT INTO table_name (Column1, Column2, ...) VALUES (Value1, Value2, ...)
When Column Names aren't specified you must pass values in the order they appear in the database table.
Insert statement should follow the below format
Insert into <TableName>(Column1,Column2) Values (Value1,Value2)
It is good practice to define the column names in the statement as it make sure the order of the columns and also in future if new column added or deleted no need to change the code
I try to write a program for updating data with id. When I write number for id (for example id=7), the program is run and works correctly. But when I write label text and convert to number, the code doesn't update and throws an error.
Here is my code:
private void yadda_saxla_update_Click(object sender, EventArgs e)
{
connect.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
// when i write "id=7" or other number data is update,
// but i want update with label text ( Convert.ToInt32( id_label.Text) )
// and gives error
cmd.Connection = connect;
cmd.ExecuteNonQuery();
connect.Close();
disp_data();
}
And the error is the following:
What can I do? Thanks...
As Others pointed it out in the comments you should not concatenate user inputs because it gives an attacking vector for SQL Injection. (or at least check for harmful inputs)
Otherwise the solution, I think, is that you should remove the ' because at the moment the command currently parsed as a varchar.
This part where id='"+Convert.ToInt32( id_label.Text)+"'" becomes where id='7' instead of where id=7
So unless your ID is stored as a varchar, this line should be changed
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id='"+Convert.ToInt32( id_label.Text)+"'";
to
cmd.CommandText = "Update Guller set gulun_adi='"+gul_adi.Text+ "', sekil='" + gulun_adi_label.Text + "' where id="+Convert.ToInt32( id_label.Text);
I don't know why the date and time is not saving on my Access Database. I follow some tutorial but it seems I'm having some problems on my code.
DateTime getdate = DateTime.Now;
String time = getdate.ToString("F");
and when I add
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity,DateTime)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "','" + time +"')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
Im stock. please help. thanks guys
The error says that there are problem on the insert into statement
Name of your column is DateTime which is a keyword. You need to change name of column. Also use Parameterized query don't concatenate strings in query.
List of reserved words.
I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}
when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.