DBNull throwing up an error - asp.net

I'm checking to see if DBNull occurs.
C# Code:
tbDuration.Text = (string)MyReader["TDuration"]==DBNull?"":(string)MyReader["TDuration"];
But I get an error on DBNull:
Error 4 'System.DBNull' is a 'type' but is used like a 'variable' C:\Visual Studio
How to check for DBNull?
Regards
Tea

DBNull is a type. What you're looking for is a static member on that type: DBNull.Value. Something like this:
tbDuration.Text = MyReader["TDuration"] == DBNull.Value ? "" : (string)MyReader["TDuration"];
Note: You also don't want to cast to a string for the purpose of the comparison. DBNull.Value will work for the actual result from MyReader[], but not if you cast it. After validating that it's not null, then you cast it.

Use DBNull.Value for checking for null values.
tbDuration.Text =
MyReader["TDuration"]==DBNull.Value?"":(string)MyReader["TDuration"]
Or, you can use:
tbDuration.Text =
DBNull.Value.Equals(MyReader["TDuration"]) ?"":(string)MyReader["TDuration"]

You should be checking for DBNull.Value, not DBNull directly.

System.DbNull.Value, is a valid reference to an instance of System.DbNull.
So you can check against the static value property of DBNull.
So It should be DbNull.Value not only DbNull
(string)MyReader["TDuration"]==DBNull.Value?"":(string)MyReader["TDuration"];

Related

Textbox dont allows null value in ASP .Net

i have column in database with Int data type, but textbox don't allows null. it gives error "Input string was not in a correct format".
objinsert.VehGrpID = Convert.ToInt32(txtVehGroupID.Text);
Use TryParse instead.
int GrpID = 0;
int.TryParse(txtVehGroupID.Text, out GrpID)
if(GrpID > 0)
objinsert.VehGrpID = GrpID;
You can just special-case out empty values. I am, of course, assuming here that an empty value should map to null.
objinsert.VehGrpID = string.IsNullOrWhiteSpace(txtVehGroupID.Text) ? null : (int?)Convert.ToInt32(txtVehGroupID.Text);
You'll also want to adjust your code to set the textbox's text accordingly.
Your question is also a bit unclear, because you say the textbox won't allow nulls, but you haven't shown us any code that adjusts the textbox text.
You can also use DBNull.Value Field. If a database field has missing data, you can use the DBNull.Value property.
check this link http://msdn.microsoft.com/en-us/library/system.dbnull.value%28v=vs.110%29.aspx
try this
int VehGrpID = Convert.ToInt32(txtVehGroupID.Text);
OR
int VehGrpIDtxtVehGroupID.Text = int.Parse(txtVehGroupID.Text);
The Text property of your textbox is a String type, so you have to perform the conversion in the code.

DateTime.TryParse in a conditional is throwing an exception

On both examples I'm giving it a String like the following: 26-03-17
Dim mvarValor As String
Dim dateVarValor As DateTime
This code snippet is throwing an exception on the TryParse:
If Not mvarValor = Nothing AndAlso DateTime.TryParse(mvarValor, dateVarValor) Then
Return Format(dateVarValor, mvarFormat)
Else
Return strNull
End If
The next code snippet is not throwing an exception, but a False like it should:
DateTime.TryParse(mvarValor, dateVarValor)
If dateVarValor = Nothing Then
Return strNull
Else
Return Format(dateVarValor, mvarFormat)
End If
Why is the first code snippet giving me an exception?
Thanks in advance!
DateTime.TryParse throws three types of exceptions
http://msdn.microsoft.com/en-us/library/9h21f14e(v=vs.100).aspx
you must be getting one of those. Here is the proper usage of DateTime.TryParse
var culture = CultureInfo.CreateSpecificCulture("en-US");
string parsedDateTime = null;
if (DateTime.TryParse(parseMe, culture, DateTimeStyles.None, out dateResult))
{
parsedDateTime = dateResult;
}
this snippet will parse the datetime without throwing an exception.
I hope this helps :)
You need to pass in a Y2K compliant date. The parser can't tell the year from 2 digits. If you pass 2003-12-25 it will validate that the date does in fact exist, but 03-12-25 is ambiguous.

Dealing with Nulls from a DataReader

I have done this in the past, but I cant remember the correct way to deal with DBNULLS.
This is vb.net
The error im getting is Conversion from type 'DBNull' to type 'Integer' is not valid.
Here is the code.
Dim reader As MySqlDataReader = command.ExecuteReader
Do While reader.Read
Dim item As New clsProvider(reader.Item("MasterAccountID"), reader.Item("CompanyName"), reader.Item("Address"), reader.Item("Postcode"), reader.Item("Telephone"), reader.Item("Fax"), reader.Item("Number_of_Companies"), reader.Item("Total_Number_of_employees"), reader.Item("MainContactName"), reader.Item("MainContactPhone"), reader.Item("MainContactEmail"), reader.Item("Fee"), Convert.ToString(reader.Item("Notes")))
list.Add(item)
Loop
reader.Close()
The issue i have is that some of the items may be empty in the DB. I'm sure in the past I have done something like
convert.ToString(reader.item("Something")
But for the life of me i cant remember.
If the column is nullable, then you should check for null:
If (reader.IsDBNull(ordinal))
See IsDBNull
Perhaps
reader.item("Something").ToString()
is what you've done before?
This isn't necessarily correct but it does deal with null strings quite effectively.
Perhaps:
IFF(reader.item("Something") != DBNull.Value, reader.item("Something"), "")
You have to first check if the column value is null (check the incoming value for DBNull). Once you know that you can decide what to do next - assign null or some other default value to your variable.
I am not sure if my VB.Net is still upto the mark but something like this should help:
Dim item As New clsProvider
item.AccountId = TryCast(reader.Item("MasterAccountID"), String)
item.SomeInt= If(TryCast(reader.Item("SomeInt"), System.Nullable(Of Integer)), 0)
Use TryCast to check if cast is possible.

I am getting Object reference Not set to an instance of an object error in my asp.net mvc aplication

I have this code there Federal_Mandate I am checking weather this MandateType is 1 or 0
if its one I am just converting this as 1 or 0
mandate.Federal_Mandate = collection["MandateType"].ToString().Equals("Federal") ? Convert.ToByte(1) : Convert.ToByte(0);
and my datbase Federal_mandate datatype has tiinyint.
is that something doing wrong i am here.. why I am gettting object reference error here?
thanks
one of mandate, collection and collection["MandateType"] is null. Set a breakpoint and find out which.
It's pretty hard to figure it out but ... couldn't it be cause your collection["MandateType"] is null?
Maybe you can change it to something like this:
mandate.Federal_Mandate = (collection["MandateType"] ?? "").ToString().Equals("Federal") ? Convert.ToByte(1) : Convert.ToByte(0);
You need to check your collection to see if its null before calling a method on it:
mandate.Federal_Mandate = Convert.ToByte(0);
if(collection["MandateType"] != null)
{
mandate.Federal_Mandate = collection["MandateType"].ToString().Equals("Federal") ? Convert.ToByte(1) : Convert.ToByte(0);
}

How to test QueryString

I have a query string called propID and I wanna check if the passed value in it is a legal integer or not to avoid throwing an error that might reveal info about my database, how can I do it?
In other words, I want something like -but in vb.net- :
IF QueryString("propID").Content.Type = "int32" Then Proceed
You could use TryParse:
Dim myInt As Integer
If Int32.TryParse(QueryString("propID").Content, myInt) Then Proceed
Dim result as boolean
result = integer.tryparse(QueryString("propID"), myintegervariable)
boolean will return true if it parsed correctly (putting the value into your myintegervariable) and will return false if the parsing failed.
You can also write is as
if integer.tryparse(QueryString("propID"), myintegervariable) then
//continue going along with myintegervariable
else
//parsing didn't work
end if
You can just use Int32.TryParse.
You could try the 'is' keyword to check the type of on object.
If QueryString("propID").Content.Type Is Int32 Then Proceed
Otherwise Int32.TryParse would work as well.
C# version:
int _PropID;
if (int.TryParse(QueryString["propID"], out _PropID))
{
//Proceed with _PropID
}

Resources