I have set my textbox = 0
<p>Credit Balance: </p><asp:TextBox ID="txtCredit" runat="server" style="width:70px" Text = "0"></asp:TextBox>
and my code behind is this:
scn.Open();
SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM UserData WHERE Username=#Username", scn);
cmd.Parameters.Add("#Username", SqlDbType.NVarChar).Value = Session["New"];
object value = cmd.ExecuteScalar();
if (value != null)
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
What i want to happen is if it has value, it will display it. if none, default value is equal to 0. But i am receiving an error
Object cannot be cast from DBNull to other types.
I suspect, value is coming as DBNull, you could guard against DBNull using Convert.IsDBNull method.
if (!Convert.IsDBNull(value))
{
txtCredit.Text = Convert.ToDecimal(value).ToString("#,##0.00");
}
Instead of using null, use DBNull.
if(value != DBNull)
{
// update textbox
}
Things you should consider:
Instead of setting the text attribute, sent its VALUE.
Verify your value before converting it. You are comparing it from null, but it is a DBNull. Check this information in addition to your Null validation.
Good luck!
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I'm trying to update multiple rows in a data grid, the code gets the job done but I still seem to get a
Object reference not set to an instance of an object
When I check the records the desired status updates accordingly for the selected records within the gridview.
private void UpdateWorkerStatus()
{
SqlCommand cmdUpdate = new SqlCommand(#"UPDATE Workers2
SET WorkerStatus = #WorkerStatus
WHERE FullName = #FullName", cn);
cmdUpdate.Parameters.AddWithValue("#WorkerStatus", SqlDbType.VarChar).Value = txtWorkerStatus.Text;
cmdUpdate.Parameters.AddWithValue("#FullName", SqlDbType.VarChar).Value = txtFullName.Text;
foreach (DataGridViewRow row in grdWorkers.Rows)
{
cmdUpdate.Parameters["#WorkerStatus"].Value = row.Cells["WorkerStatus"].Value.ToString();
cmdUpdate.Parameters["#FullName"].Value = row.Cells["FullName"].Value.ToString();
cmdUpdate.ExecuteNonQuery();
}
}
thank you in advance! :)
private void UpdateWorkerStatus()
{
SqlCommand cmdUpdate = new SqlCommand(#"UPDATE Workers2
SET WorkerStatus = #WorkerStatus
WHERE FullName = #FullName", cn);
cmdUpdate.Parameters.AddWithValue("#WorkerStatus", SqlDbType.VarChar).Value = txtWorkerStatus.Text;
cmdUpdate.Parameters.AddWithValue("#FullName", SqlDbType.VarChar).Value = txtFullName.Text;
foreach (DataGridViewRow row in grdWorkers.Rows)
{
cmdUpdate.Parameters["#WorkerStatus"].Value = row.Cells["WorkerStatus"].Value!=DBNull.Value? row.Cells["WorkerStatus"].Value.ToString():"";
cmdUpdate.Parameters["#FullName"].Value = row.Cells["FullName"].Value!= DBNull.Value ? row.Cells["FullName"].Value.ToString():"";
cmdUpdate.ExecuteNonQuery();
}
}
Since you don't supply us with the information of where the exception is thrown, I'm going to assume it's on one of the .ToString() calls as those are the most likely. Probably one of the values for WorkerStatus or FullName are null, resulting in the exception when you call the .ToString() method.
I would check the values for null before calling the .ToString(). This enables you to fill the parameter values with something meaningful if the value you are trying to read is null:
if (row.Cells["WorkerStatus"].Value != null)
cmdUpdate.Parameters["#WorkerStatus"].Value = row.Cells["WorkerStatus"].Value.ToString();
else
cmdUpdate.Parameters["#WorkerStatus"].Value = string.Empty // or some meaningful default value of your chosing
You can reduce this statement to one line using this:
cmdUpdate.Parameters["#WorkerStatus"].Value = (row.Cells["WorkerStatus"].Value != null) ? row.Cells["WorkerStatus"].Value.ToString() : string.Empty;
And of course you should do the same for FullName.
Try this,Instead of .ToString() use Convert.Tostring( row.Cells["FullName"].Value)
Same for "WorkStatus"
How to set Default Value as Value of SqlCommand SqlParameter?
SqlCommand is the class contained in System.Data.SqlClient
My Schema does not accept DBNull.Value as value
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1) { Value = DBNull.Value });
As lboshuizen points out, if your "schema" isn't taking null, or the parameter of the stored procedure or query cannot be null, trying to give it a null value will likely fail. In this case, you need to see why you are trying to set it to null if you know it doesn't accept it. I would surmise an empty string as opposed to null would work, or something else that is sensible.
The SqlParameterCollection property Parameters has an AddWithValue method:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
You can simply insert null and that will be handled for you:
command.Parameters.AddWithValue("#parameter", null);
If you cannot provide a null, you can provide something like an empty string:
command.Parameters.AddWithvalue("#parameter", "");
You also very rarely need to specify the data type using this mechanism.
If the schema doesn't accept null it indicates that the column is mandatory and requires a sensible value.
Using a default value for a column is a property of the schema.
So either alter the schema to provide a default.
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
Choose a valid (not null) default value in your application code and use it as a value in the parameter.
const string default = "unknown";
...
SqlCommand command = new SqlCommand();
command.Parameters.Add(new SqlParameter("column_1", SqlDbType.VarChar, 1)
{ Value = default });
Note: Changing the schema to accept NULL is considered cheating :-)
Does a NULL value for a (string) column in the database would return a null value in the dataset record in C# (by default)? Or would it turn into an empty string in the dataset?
In .NET depending on what technologies you use, a NULL value will be returned as null or as DBNull.Value.
When using ADO.NET (System.Data), a database NULL value will generally be returned as DbNull.Value, whereas in (for example) Entity Framework, it will be returned as null.
If you are not doing any other processing, the value will not be returned as an empty string and in no case as the string value "null".
Normally it will return the value DBNull.Value or throw a InvalidCastException. Depending on what you are going to it could turn the DBNull.Value in to a null, but usually when stuff like that happens it really is doing the DBNull.Value check for you and just hiding it. It would not be hard to make a extension method of your own that did it too.
public static string GetStringWithNullCheck(this IDataReader reader, int index)
{
if(reader.IsDBNull(index))
return null;
return reader.GetString(index); //If we called this on a record that is null we get a InvalidCastException.
}
This distinction between null and DBNull.Value is most useful when calling ExecuteScalar(), this allows you to tell the diffrence between "no records returned" and "record returned but the DB contained NULL as the value"
using(var cmd = new SqlCommand(query, connection))
{
var result = cmd.ExecuteScalar();
if(result == null)
{
//0 rows where returned from the query
}
else if(result == DBNull.Value)
{
//Rows where returned but the value in the first column in the first row was NULL
}
else
{
//Result is the value of whatever object was in the first column in the first row
}
}
I have a field clube varchar(50) that is by default NULL, and it it's not notnull so it accepts null values. What I need to know is, if I have a value already on this field and I want to make an Update and set it's value with null, how would I do that?
I tried to set null the value of a string but didnt worked.
IF some condition become true, I want to set this field as NULL by an Update.
And as obvious, if the condition become false, I will pass a value and NOT null value. So I need to do it using MySqlcommand Parameter. Like:
sql = "UPDATE usuarios SET nome = #nome";
cmd.CommandText = sql;
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = `variable`;
if the condition is true = variable = null else variable != null.
To set the value to null:
cmd.Parameter.Add(New MySqlParameter("#nome", MySqlDbType.VarChar)).Value = DBNull.Value;
Here's the answer I found:
cmd.Parameters.Add(new MySqlParameter("#nomeclube", MySqlDbType.VarChar)).Value = !String.IsNullOrEmpty(usr.Nome_Clube) ? (object)usr.Nome_Clube : DBNull.Value;
Simple. Just set it to NULL:
UPDATE table SET clube = NULL WHERE .....
I have an insert stored procedure like this
if exists(select EmailId from Profile_Master where EmailId=#EmailId)
set #result=-1
else
begin
set #result=0
insert into Profile_Master(FirstName,LastName,Dob,Gender,MobileNo,Country,State,EmailId,Password)
values
(#FirstName,#LastName,#Dob,#Gender,#MobileNo,#Country,#State,#EmailId,#Password)
set #id=SCOPE_IDENTITY()
return
end
pid = cmd1.Parameters.Add("#id", SqlDbType.Int);
pid.Direction = ParameterDirection.Output;
cmd1.ExecuteNonQuery();
int res = Convert.ToInt32(pid.Value);
I am catching the value of last inserted record but i am getting an error like
Object cannot be cast from DBNull to other types.How to catch the value of last inserted record?
Do a null-check before you try to convert the value.
if( pid.Value is DBNull )
{
// Do alternative route.
}
else
{
int res = Convert.ToInt32(pid.Value);
}
or:
if( ! pid.Value is DBNull )
{
int res = Convert.ToInt32(pid.Value);
}
Well, clearly we can assume that pid.Value is equal to DBNull.Value and cannot be converted to type int
You need to check what the sp does adn what it returns from the Database.