int does not contain a constructor that takes 1 arguments - c#

Hey guys this bug has been puzzling me for like 4 hours, and nothing I've tried works.
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int.ToString());
id.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(id);
cmd.ExecuteNonQuery();
book.BookId = new int(id.Value.ToString()); // <------ERROR
The error is:
int does not contain a constructor that takes 1 arguments
Here are some of the other things I have tried:
int x = id.value.ToString();
int xi = Convert.ToInt32(x);
book.BookId = x;

Maybe this one?
book.BookId = Int32.Parse(id.Value.ToString());

Since none of the answers so far have actually explained what you are doing wrong - this occurs because you are trying to call a constructor of int and pass an argument. As you can see here, there is no int constructor that accepts a string argument (or any other type, for that matter).
There are a few ways of converting a string to an integer, but the most robust (as already posted by Thomas) is to use Int32.TryParse.

If you are 100% sure that your string contain an integer and you are ok with throwing an exception else, you can do :
string id = "55";
int x = Int32.Parse(id);
Else, cleaner you can manage the case where the string is not an integer :
string id = "55";
int x = 0;
if(!Int32.TryParse(id, out x))
{
//Manage the special case here where id is not a int
}

Try this
book.BookId = Convert.ToInt32(id.Value);

You have to try any of this:
book.BookId = Int32.Parse(id.Value.ToString());
OR
book.BookId = (int)id.Value.ToString();
OR
book.BookId = int.Parse(id.Value.ToString());

You must check to make sure that id.Value is not NULL. After you've made sure, then this should work:
book.BookId = Convert.ToInt32(id.Value);
or even
book.BookId = (int) id.Value;
Edit
If Int32.Parse() is throwing a format exception, you must be giving it something that is not an integer. You say you're confident that it's not NULL, so what is it?

From my point of view you are using ToString() to much. Try this:
SqlParameter id = new SqlParameter("#bookId", System.Data.SqlDbType.Int);
id.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(id);
cmd.ExecuteNonQuery();
Int32.TryParse(id.Value.ToString(),out book.BookId);

This statement doesn't look correct
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int.ToString());
I think you should change it either Int or String
SqlParameter id = new SqlParameter("#bookId",System.Data.SqlDbType.Int);
Just change your statement
book.BookId = Convert.ToInt32(id.Value.ToString());

Related

How can convert DBObject value into long

I want to convert DBObject value into long. I have value in db something like id = 24100001000001.
I'm using this code:
String totalcount = "SELECT MAX(id) FROM table";
SqlCommand cmd1 = new SqlCommand(totalcount, con);
cmd1.ExecuteNonQuery();
long count = (long)(cmd1.ExecuteScalar());
Using this code, I'm getting an error:
System.InvalidCastException: sSpecified cast is not valid.
at Default.method1(Object sender, EventArgs e) in c:\Users\aBhiShEkrANAa\Desktop\ABC\Prroject\Default.aspx.cs:line 43
I just want this id value into long.
Little bit simpler approach will be to use right type for the job:
var value = (long?)command.ExecuteScalar();
If you want to return default value instead of nullable:
var value = (long?)command.ExecuteScalar();
return value.GetValueOrDefault();
Nullable value will handle DbNull and using nullable will provide more information for other developers/readers.
Notice that actual value under object returned by ExecuteScalar is a long, using Convert.ToInt64 will be much overhead, because converting do much more work.
It might contain Null values. So it would be better to use Convert instead of cast in this case, or even would be better to use something like this:
var temp = cmd1.ExecuteScalar();
temp = (temp == DBNull.Value) ? null : temp;
long count = Convert.ToInt64(temp);

how to assign int value to SELECT database string?

I used DataAdapter for use SELECT common to choose rows of Table
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter("SELECT * FROM Table WHERE dayNum = #dayNum", objConnection); //here dayNum must be equal to 10; dayNum = 10
I want assign an integer value to #dayNum
for example
int intDay = 10;
objCommand.Parameters.AddWithValue(intDay.ToString(),"#dayNum");
but it don't work
how can fix this problem?
The first argument is the parameter name and the second the value, so:
objCommand.Parameters.AddWithValue("#dayNum", intDay); // use the correct type not string
Remove the .ToString(). Try this:
objCommand.Parameters.AddWithValue("#dayNum",intDay);

C# SqlParameters Short Hand

I'm taking data that is in a List of Record objects and putting their contents in to a database:
// Processes a Record and adds it to the database
public bool addRecord(SqlConnection db, List<Record> recordsToAdd)
{
using (SqlCommand command = db.CreateCommand())
{
foreach (Record record in recordsToAdd)
{
// Set the query command text
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER (PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC) VALUES ('#PRODCODE', '#TOTFREE', '#TOTPHYS', '#ITEMTYPE', '#PRODESC')";
SqlParameter param1 = new SqlParameter("#CURSTAT", record.curstat);
SqlParameter param2 = new SqlParameter("#ITEMDESC", record.itemdesc);
SqlParameter param3 = new SqlParameter("#PRODCODE", record.prodcode);
SqlParameter param4 = new SqlParameter("#TOTFREE", record.totfree);
SqlParameter param5 = new SqlParameter("#TOTPHYS", record.totphys);
SqlParameter param6 = new SqlParameter("#ITEMTYPE", record.itemtype);
SqlParameter param7 = new SqlParameter("#PRODESC", record.proddesc);
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
command.Parameters.Add(param4);
command.Parameters.Add(param5);
command.Parameters.Add(param6);
command.Parameters.Add(param7);
// Execute the query
command.ExecuteNonQuery();
}
return true;
}
}
Here's my Record class:
class Record
{
public string curstat { get; set; }
public string itemtype { get; set; }
public string itemdesc { get; set; }
public string prodcode { get; set; }
public string proddesc { get; set; }
public string totfree { get; set; }
public string totphys { get; set; }
}
Just from looking at the code, I've got a feeling that there is a shorter way of achieving this.
But secondly, I'm not even sure if I've done it correctly that the #PARAMETER values are being replaced.
If I view the contents of command, it still shows the query string with the # parameters.
Also, I'm getting this error on command.ExecuteNonQuery():
String or binary data would be truncated.
The statement has been terminated.
So, my questions are:
Is there a shorter way to set and add multiple parameters to the query?
What could be causing the error?
You have a bigger constructor:
command.Parameters.Add(
"#CategoryName", SqlDbType.VarChar, 80).Value = "toasters";
Using the method AddWithValue will make the code a little bit shorter:
command.Parameters.AddWithValue("#CURSTAT", record.curstat);
//...
I do it a bit differntly.
I have both a extension method and a static method to create SqlParameters.
public static SqlParameter ToParam(this object v,string name){
return new SqlParameter(name,v);
}
Then I do something like this:
var p = new List<SqlParameter>();
p.Add(record.curstat.ToParam("#curstat"));
p.Add(record.itemdesc.ToParam("#itemdesc"));
//etc...
command.Parameters.AddRange(p.ToList());
The String or binary data would be truncated. most likely means your putting too many characters into one of your VARCHAR fields. I.e., if your column PRODDESC is a VARCHAR(50), and the string you're trying to insert is 70 characters, you will see that error.
Others have addressed alternative ways of doing the parameters so you can reduce the lines of code.
For a shorter syntax, you can use AddRange method of the SqlParameterCollection class. It means:
command.Parameters.AddRange(new [] {
new SqlParameter(...),
new SqlParameter(...),
new SqlParameter(...) });
The error you're getting indicates that a string value doesn't fit in the table column or parameter, and is being truncated. You should check the length of the column in comparison to the data being inserted, or specify the length of parameters using another overload of the SqlParameter constructor.
If you wanted to use the following class:
Class MyParam
{
public string name {get;set;}
public object value {get;set;}
}
then you could have a List called myParams and do:
foreach(var p in myParams) command.Parameters.AddWithValue(p.name, p.value);
You obviously have to link the parameters and values somehow and there's no way around that. But if you do it in a class like this then the code that actually does the action is only one line long.
I think the message
String or binary data would be truncated.
The statement has been terminated.
comes from an error in your Command Text: in the SQL Query the parameters, even if they are strings, do not need to be quoted.
Replace the command with this
command.CommandText = #"INSERT INTO SMDGROUP_STPRODMASTER
(PRODCODE, TOTFREE, TOTPHYS, ITEMTYPE, PRODESC)
VALUES (#PRODCODE, #TOTFREE, #TOTPHYS, #ITEMTYPE, #PRODESC)";
To shorten the code i think you could add somewhere (for example in your record class or in an helper class) a method that creates an array of parameter from a record object and then call the AddRange function. It should keeps this function cleaner and you could use it also in other part of you code.
In regards to the error, it's a truncation problem i.e. the length of your parameter is longer than what your column can hold. To resolve this, be more specific when passing your parameters e.g. new SqlParameter("#MyParameter", SqlDbType.VarChar, 30).
Personally I don't think their is anything wrong with how your currently adding the parameters it's readable and does the job. If, however, you want to reduce the amont of lines of code in your function you could either go with what #Royi has suggested or simply package up the parameter adding into another method.
This worked for me:
comando.Parameters.Add(
"#EmailAddress", SqlDbType.VarChar).Value = EmailAddress;

Problem on querystring in SQL cmd

I have the next code:
private int bla(out int itemsMin, out int purchase)
{
string ID = (Request.QueryString["Ttrsid"] ?? "0").ToString();
{
SqlConnection connection = new SqlConnection("Data Source=*****;Initial Catalog=****;User ID=****;Password=*****;Integrated Security=False;");
string commandtext = "SELECT Min FROM myItems WHERE itemId=#ID";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
itemsMin = (int)command.ExecuteScalar();
string commandtext2 = "SELECT COUNT (*) FROM purchase";
SqlCommand command2 = new SqlCommand(commandtext2, connection);
purchase = (int)command2.ExecuteScalar();
}
return 0;
}
The code is for two labels that i use - one to get the minimum number (itemsMin), and the other is for the count of the purchase.
I'm using the querystring to get the values by the itemid that the user watching on him now.. (from the address bar (for example: items.aspx?Ttrsid=5 so i want to see the minimum number of the Ttrsid = 5).
Everything works fine. when i'm on the Ttrsid = 1 , Ttrsid = 2 - i get what i want, but when i'm enterd to the Ttrsid = 3 and so on - that's give me the error:
System.NullReferenceException
To the line:
itemsMin = (int)command.ExecuteScalar();
.. and it's not null.. the item have all the required fields like Ttrsid = 2 .... so what wrong here?
The next code is the use of the command above:
int i, p; // variable need not be initialized
Console.WriteLine(bla(out i, out p));
if (i < p)
{
haha.Visible = true;
}
else
{
haha2.Visible = true;
}
Console.WriteLine(i);
Console.WriteLine(p);
i = itemsMin , p = purchase .
I'm guessing there is no matching row in the db, so no rows returned. Sanity-check the result from ExecuteScalar - in particular, check it for null before casting to int. It is also possible that the column contains a null, but maybe I'd expect DBNull.Value for that.
Also - use using on all the IDisposable objects here; the connection and command in particular.
I assume below pasted variable is a int type variable
purchase = (int)
Hence you may not be able to convert null values to an integer so try it changing the sql command as below
SELECT isNull(COUNT (*),0) FROM purchase
#Marc I'm really sorry about it
Don't you want to specify a column name next to the min statement? As below
SELECT Min(columnName) FROM myItems WHERE itemId=#ID ?

Converting Request.QueryString to integer

How do i convert a Request.Query string to an integer value. I've tried all the Convert.ToInt32 and Int32.Parse but it says Input string is not in the correct format. I am using the string value as an input to a stored procedure which takes in only integer types for that field.
Here's a part of the code-
string rid=Request.QueryString["RID"];
lblRID.Text = rid;
int id= Int32.Parse(rid);
if (lblRID.Text!= null)
SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection);
myCommand.Parameters.AddWithValue("#RID",id); //RID is int in database and stored procedure
myCommand.CommandType = CommandType.StoredProcedure;
int foo;
int.TryParse(Request.QueryString["foo"], out foo);
or just like you say, int.Parse should convert to int
Could you post some code here ?
The answer thesedays varies based on what framework you're using as msft has made query params part of the view attribute model now for binding (ref: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromqueryattribute?view=aspnetcore-3.1).
You can still access most things via httpcontext for the sake of example.
var fooIsInt = int.TryParse(HttpContext.Request.Query["foo"], out var foo);
Original Example for webforms in .net 2.0
Quick and dirty (and in a page load because this is an example, you should be able to work out what's happening from this)
<script runat="server">
private void Page_Load(object sender, System.EventArgs e){
string test = Request.QueryString["foo"];
//Convert the query string you captured to an int and store it in an int.
int intTest = Convert.ToInt32(test);
Response.Write(intTest.GetType() + "<br>" + intTest);
}
</script>
How about looking on the input that you provide to Int32.Parse?
We use a base class from which every Page inherits. We have the following method that returns integer values from querystring params:
protected int FetchQueryStringIdentifierByKey(string key)
{
int identifier;
var isInt = int.TryParse(Request.QueryString[key], out identifier);
return (isInt) ? identifier : 0;
}
Credit goes to Jayson Knight for his research into his original bench-marking results under .NET 2.0.
string id = Request.QueryString["RID"].ToString();
userid=Convert.ToInt32(id);
How about using TryParse like this:
string rid = Request.QueryString["RID"];
int id = 0;
if (!string.IsNullOrEmpty(rid) && Int32.TryParse(rid, out id))
{
lblRID.Text = rid;
SqlCommand myCommand = new SqlCommand("usp_NewResource_get", myConnection);
myCommand.Parameters.AddWithValue("#RID",id);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Execute...
}
The problem is that the value passed in the query string with the RID parameter is not a number, so it cant be parsed to an int. E.g you have ?RID=hello or maybe no RID parameter at all (in which case the value is null). Inspect the querystring to see the actual value passed.

Categories

Resources