I have read
What is the difference between null and System.DBNull.Value?
INSERT / UPDATE data using DBNull or null?
and similar Q&A but don't quite understand this.
The problem:
tableAdapter allow's me storing null into not nullable fields (AllowDBNull = false).
What I need to check?
I can check for
string.Lenght == 0
string.IsNullOrEmpty(string)
string.text = ""
before update command but want to know why table adapter is letting me storing NULL
it's actually storing someTextBox.Text = "" when needed to throw exception null not allowed for some field.
I have exactly same problem Dataset allowing Null values even when AllowDBNull = False? but there are no solution.
Thanks
I would need more code to see for sure what you are doing, but:
public static object GetValue(string value) {
if (!String.IsNullOrEmpty(value)) {
return value;
}
return DBNull.Value;
}
Would that solve your issues?
Related
I'm trying to insert record using C# and SQL, but i got this error when date column is empty, i searched for a similar cases but didnt solve it yet. It inserts 01/01/1900, the column in table is Datetime any idea or similar case link.
[HttpPost]
public HttpResponseMessage save (Education edu)
{
Dictionary<string, object> xmt = new Dictionary<string, object>();
xmt.Add("#Staff_Key", edu.Staff_Key);
xmt.Add("#Type_Education", edu.Type_Education);
xmt.Add("#Qual", edu.Qual);
xmt.Add("#Uni", edu.Uni);
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
xmt.Add("#Notes", edu.Notes);
obj.ExecNonQuery(
#"insert into HR_DocEducation (Staff_Key,Type_Education,Qual,Uni,Date_Issue,Notes)
values (#Staff_Key,#Type_Education,#Qual,#Uni,#Date_Issue,#Notes) ",xmt);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
return response;
Hassan,
I had the same issue, the trick in addition to use the nullable DateTime DateTime? object is correcting the ternary operator as follows:
xmt.Add("#Date_Issue", edu.Date_Issue == null ? (object) DBNull.Value : (object)edu.Date_Issue);
instead of
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
As said by Astha Srivastava, you can find a short description of DateTime's behavior on null values.
Question: DateTime “null” value
A possible way is to use the propertie DBNull.Value which is referencing to a value used on databases. I can recommend to use that when using SQL Commands.
After a short lookup I found a similar question of yours, using the DBNull.Value as example. Look it up and if it might help you give the answer a upvote.
Question: Nullable DateTime and the Database
I have a linq query:
var capacityQuery = from Info in mySQLDataTable.AsEnumerable()
where Info.Field<object>("location") == Location.ID
orderby Info.Field<DateTime>("date")
The line "where Info.Field("location") == Location.ID" is where I am having problems
My Question is. How do I do a comparison in the where statement that might be either a DBNull.Value or an int value on either side
Below is for reference:
Location is a custom class. The ID returns an object.
private int? addressID;
public object ID {
get
{
if (addressID == null)
return DBNull.Value;
else
return addressID;
}
}
The reason it has to be DBNull is because it is coming from a database. The "table" is also being filled in from a database.
I know == in this case is wrong because its comparing the references which is obviously false.
I know object.equal(var1, var2) should work but it doesnt which im guessing is because they are 2 different objects.
The values could be an int or DBNull both on the table side and the class side.
This is in a foreach loop so I use the same query where Location has an int value or when it has a DBNull value.
Again My Question is. How do I do a comparison in the where statement that might be either a DBNull.Value or an int value on either side
Use
private int? addressID;
public object ID {
get
{
return addressID.HasValue ? addressID.Value as object : DBNull.Value;
}
}
instead. This way, if addressID has not been initialized or if it has been deliberately set to null, the ID property will return a DBNull.Value. Otherwise, it will return an int, but you have to cast it yourself from object to int or int?.
Having said that, creation of the null has been called "a billion dollar mistake" by the author, but by now I think it is in the trillions. You should return an int? datatype from the database if you can, in which case, the comparison will always work. I am not sure which ORM do you use, but Dapper and linq2db handle this scenario correctly as far as I know.
I have a custom class Diary, which has a nullable property DeadlineType
On one of my Forms I have a ComboBox in DropDownList mode, which is populated with all the possible values that DeadlineType can take. When a Diary is selected, the form is populated with all the properties, but I have an issue with the DeadlineType property in that, when it is null, it requires more code than I believe it should i.e.
if (amendDiary.DeadlineType != null)
{
cboDeadlineType.Text = amendDiary.DeadlineType.ToString();
}
else
{
cboDeadlineType.Text = null;
}
I am sure there must be a more concise way to achieve this, or certainly hope so, because this scenario is repeated a lot throughout my application i.e. posting nulls to ComboBoxes.
I did try
cboDeadlineType.Text = amendDiary.DeadlineType.ToString() ?? null
But that gives an 'Object not set to an instance' error.
Try this:
cboDeadlineType.Text = (amendDiary.DeadlineType ?? "").ToString();
Note that setting the ComboBox.Text to null means the same as setting it to "" (The combo Text is empty in both cases).
Another solution is use the Convert.ToString method:
cboDeadlineType.Text = Convert.ToString(amendDiary.DeadlineType);
With that solution, if the input is null, the cboDeadlineType.Text is assigned exactly to null.
try
cboDeadlineType.Text = amendDiary.DeadlineType!=null ?amendDiary.ToString() :"";
Hopefully this is an easy one. Is there a way to test for an "empty" field using DataRow? The following work fine for testing against a field with null values, unfortunately, the column I'm dealing with are either populated with data or are just "empty". Is there an approach in C# I'm missing? Thanks
if (Particle.Tables.Count == 0 || pDr.ItemArray[1].ToString() == "")
tblParticle.Append("No Data");
you can use stirng.isNullorEmpty to check for empty fields. String.isNullorEmpty
if (Particle.Tables.Count == 0 || string.isNullorEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
.
if (string.IsNullOrEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
else
{
//else do something else
}
checking for NULL will not hurt keep in mind that Null and Empty are two different things
See DataRow.IsNull method - it accepts a column name or index
and returns whether it is NULL
The following assumes we are talking about a string (VARCHAR/CHAR) column:
If you don't care if it is null or an empty string, and always want an empty string back, you can use DataRow["name"].ToString()
If you want your string object to become null or empty just like the field value, you can use DataRow["name"] as string
If you want to get an exception in case of NULL, you can use (string) DataRow["name"]
I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.
This is the code that isn't working as expected when the "fk_id" field is null:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
//never reaches here
}
Note: using an int index instead of the Columns.IndexOf() isn't the issue.
Also does the "{}" have some other name in C#?
To check a column for DBNull in a DataSet, you can use the IsNull method:
if (resultSet.Rows[0].IsNull("fk_id"))
Your comparison against null is probably failing because DataSets don't use null to represent a "database NULL" value - they use DBNull.Value. If you need your code to work the way you've presented it, try this:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == DBNull.Value)
try
{
if (DT.Rows[0][0] != null)
{
//your code
}
}
catch
{
MessageBox.Show("AUTHANICATION FAILED.");
}
Please use:
dataTable.Select("FieldName is NULL")
this will give you the DataRows with null values in FieldName column.