Making maskedtextbox to read NULL from SqlDataReader - c#

I have this short code which I use to read data into maskedtextbox and then (which isn't part of this code) UPDATE them via SqlCommand
SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce=" + tentoradek, spojeni);
spojeni.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();
if (precti.Read())
{maskedTextBox2.Text = precti.GetDateTime(24).ToShortDateString(); // i need to improve this part
}
But know if maskedTextBox2 value is NULL it gives me an error that:
Data is Null. This method or property cannot be called on Null values.
I would like to ask you, what should I change with this code to make it read Null?
Thanks in advance.
Here is the snippet of the code which I used to do for INSERT INTO It is marked as an answer.

Check if the SqlDataReader contains a DBNull value using the IsDBNull method on the column 24 and act appropriately returning an empty string or the not null value
if (precti.Read())
{
maskedTextBox2.Text = precti.IsDBNull(24) ?
string.Empty :
precti.GetDateTime(24).ToShortDateString();
}

Related

How to spot an empty access field with data reader C#

I'm trying to create a method that returns a string from my db that fulfills my conditions.
The first condition is working.
But, the second condition is that part of entry in access is empty, at least one field.
This is my code:
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT numNumber, numLocation " +
"FROM tblNumbers " +
"ORDER BY numID ";
OleDbDataReader dataReader = datacommand.ExecuteReader();
while (dataReader.Read())
{
if (MatchServiceLetters(dataReader.GetString(0))) // && dataReader.GetInt32(1) == null?/)
}
return dataReader.GetString(0);
If the int field is empty, the comparison to null isn't working. so how can I know if it is empty?
From MSDN:
No conversions are performed; therefore, the data retrieved must already be a 32-bit signed integer.
Call IsDBNull to look for null values before calling this method.
So you would use:
if(!dataReader.IsDBNull(1))
{
return dataReader.GetInt32(1);
}
else
{
return 0; // or better yet, make your method return Nullable<int>
}

Unable to insert null values in nullable column via stored procedure in C#

I have a SQL table where column is set to null. Now I am passing the null value from code via stored procedure and it throws an error which is, Procedure or function 'MyStoredProcedure' expects parameter '#Parameter', which was not supplied.
Now Confusing part for me is, if I add null condition and than pass DBNull.Value, it works fine but if I pass direct parameter which could be null than it throws error. I am trying to understand why? Am I missing something here?
Note: Just for information, passing parameter could be null based on the requirement.
Code:
string connString = _dbContext.Database.Connection.ConnectionString;
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
scheduledEndDateTime = !string.IsNullOrEmpty(bulkUpdateSchedule.EndDate) && !string.IsNullOrEmpty(bulkUpdateSchedule.EndTime)
? (DateTime?)
Convert.ToDateTime(bulkUpdateSchedule.EndDate + " " + bulkUpdateSchedule.EndTime)
: null;
//This Fails
cmd.Parameters.AddWithValue("#scheduledEndDateTime", scheduledEndDateTime);
//This Works
if (scheduledEndDateTime != null)
{
cmd.Parameters.AddWithValue("#scheduledEndDateTime", scheduledEndDateTime);
}
else
{
cmd.Parameters.AddWithValue("#scheduledEndDateTime", DBNull.Value);
}
cmd.ExecuteReader();
connection.Close();
}
Stored Procedure:
ALTER PROCEDURE [dbo].[InsertScheduledBulkUpdateRecords]
#scheduledEndDateTime DATETIME,
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ScheduledBulkUpdate (ScheduledEndDateTime)
VALUES (#scheduledEndDateTime)
END
Table Structure screen shot:
You've pretty much answered your own question null and DBNull.Value are different things. Where DBNull.Value means something to the database provider than null doesn't.
From MSDN on DBNull:
Do not confuse the notion of null in an object-oriented programming
language with a DBNull object. In an object-oriented programming
language, null means the absence of a reference to an object. DBNull
represents an uninitialized variant or nonexistent database column.

get value in variable from table

int value2;
using (SqlConnection dataConnection = new SqlConnection(#"Data Source=MANNAN-PC\SQLEXPRESS;Initial Catalog=WareHouse;Integrated Security=True;"))
using (SqlCommand dataCommand = new SqlCommand("Select Sum(I_Quantity) from Itemswork where I_Detail='" + maskedTextBox2.Text + "' and Order_No ='" + maskedTextBox1.Text + "'", dataConnection))
{
dataConnection.Open();
value2 = Convert.ToInt32(dataCommand.ExecuteScalar());
}
It shows the Error of DBnull because the column from which I'm getting the value is already int. I want to know what is the other way to get that value in variable's value2 definition.
Check the remarks section here:SqlCommand.ExecuteScalar Method
value2 = (Int32)dataCommand.ExecuteScalar();
As #Soner states you should be using parameterized queries to reduce the issues relating to SQL Injection etc. One of the problems you're actually experiencing is that the result being returned is NULL.
The SUM where no columns are returned is not 0, what you could do is change your output to check whether the returned value IsDbNull before trying to parse it into an integer. (See Unable to cast object of type 'System.DBNull' to type 'System.String` - although it's parsing to string the logic is the same)
ExecuteScalar will return
null if there is no result set
otherwise the first column of the first row of the resultset, which may be DBNull.
(Example modified from linked question and not syntax checked)
var tempObject = dataCommand.ExecuteScalar();
value2 = (tempObject == null || Convert.IsDBNull(tempObject) ? (int) tempObject: 0;

How to read nvarchar(x) into String when null values are allowed?

I have a SQL table with a column of type nvarchar(20) and want to read that column using SqlDataReader. Looks like the only way to do this is to use GetSqlChars() followed by ToSqlString():
String result = reader.GetSqlChars(index).ToSqlString().Value
the problem is that if the stored value happens to be null (and that's valid for my case) I get
[SqlNullValueException: Data is Null. This method or property cannot be called on Null values.]
System.Data.SqlTypes.SqlString.get_Value() +3212527
so I have to first check what the value returned by ToSqlString() returns in IsNull():
SqlString asSqlString = reader.GetSqlChars(index).ToSqlString();
String result = asSqlString.IsNull() ? null : asSqlString.Value;
which works but requires lots of extra code and looks really inelegant.
Is there a more elegant way to achieve the same effect?
Perhaps:
var value = reader.IsDBNull(index) ? null : reader.GetString(index);
Or even shorter:
var value = reader[index] as string;
You can use the GetValue() method:
// define your query
string query = "SELECT YourField FROM dbo.YourTable WHERE ID = 1";
using(SqlConnection conn = new SqlConnection("......"))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
string fieldValue = rdr.GetValue(2).ToString();
}
}
conn.Close();
}
GetString method is specifically coded to throw an exception if the database value is null. This is by design.
The docs for GetString state:
Call IsDBNull to check for null values before calling this method
On the other hand, if you use GetValue() and you end up with a DBNull object as your value, the DBNull.ToString method automatically returns String.Empty.

Update command error

I want to update a row by code in my form. Maybe some columns are null. So while command is
executing, an error will rise and say Incorrect syntax near the keyword 'where':
SqlCommand Update = new SqlCommand("Update Table_065_Turn SET Column02=" + Row["Column48"] + " , Column15= " + Row["Column15"].ToString() +
" where ColumnId=" + StatusTable.Rows[0]["ColumnId"], Con);
Update.ExecuteNonQuery();
I know this error will be displayed because Row["Column15"] is null.
How can I check if the column in datarow is null; of course without any extra variable or commands before Update command.
I mean check columns exactly in update command.
I would recommend using SqlParameters, also SqlCommand implements IDisposable so you should wrap it up in a using statement e.g.
using (SqlCommand update = new SqlCommand("Update Table_065_Turn SET Column02=#Col2, Column15=#Col15 where ColumnId=#ColId", con))
{
update.Parameters.AddWithValue("#Col2", Row["Column48"]);
update.Parameters.AddWithValue("#Col15", Row["Column15"]);
update.Parameters.AddWithValue("#ColId", StatusTable.Rows[0]["ColumnId"]);
update.ExecuteNonQuery();
}
Also you might be better actually validating the fields before you execute the query unless null is a valid column value.
I suspect you have to "replace" .net null with database keyword NULL, e.g.
string sql = "Column15 = " + (row[15] == null ? "NULL" : row[15].ToString()) in your case, but the much better way is to use Parameters as written by James, also keep in mind someone could provide hamful strings to your query:
row[15] = ";DROP DATABASE; --" would be enough in your case to cause all your data to be lost ;) (see "SQL injection" on your favorite search engine
you could use
var value = "" + Row["columnname"] ;
so ,you do not need to check the object is null
it is safe..
You could do like this:
string filterString;
if (StatusTable.Rows[0]["ColumnId"]!=System.DBNull.Value)
filterString= #" WHERE ColumnID= StatusTable.Rows[0]["ColumnId"]";//I assume the value returned is a string
else
filterString="";
And then you can just append the filterString variable to your SQLCommand string.

Categories

Resources