Logic to check for Null Value in Multiple Textboxes - c#

Hi guys, probably a simple one.
Using C# .Net 4.0 and Visual Studio 2012 Ultimate.
Got the following code:
string part = "";
part = txtIOpart.Text;
txtBatchCV.Text = txtBatchIO.Text;
txtPartCV.Text = part;
txtExternalCV.Text = Sqlrunclass.SplitSpec_External(part, pg);
txtInternalCV.Text = Sqlrunclass.SplitSpec_Internal();
txtABSCV.Text = Sqlrunclass.SplitSpec_cvABS();
txtOilCV.Text = Sqlrunclass.SplitSpec_OilSeal();
txtBarCV.Text = "*" + Sqlrunclass.SplitInfo_ASno(part, pg) + "*";
txtBarNumCV.Text = txtBarCV.Text;
txtLocnCV.Text = Sqlrunclass.SplitInfo_Location();
txtFitsCV.Text = Sqlrunclass.SplitInfo_Desc();
txtHeightCV.Text = Sqlrunclass.SplitSpec_Height();
txtDiameterCV.Text = Sqlrunclass.SplitSpec_Diameter();
txtCirclitCV.Text = Sqlrunclass.SplitSpec_Circlit();
picTypeCV.Image = ftpclass.Download("CVspecType" + Sqlrunclass.SplitSpec_TypeCV() + ".jpg", "ftp.shaftec.com/Images/TypeJpg", "0095845|shafteccom0", "4ccc7365d4");
if (txtBatchCV.Text == null || txtBatchCV.Text == "")
{
txtBatchCV.Text = "ALL";
}
As you can see at the bottom I'm checking the batch, but I need to check all of the data thats being set by a bunch of methods. Each one will have a different txt output if it sees a null or blank txt. Is there anyway to shorten this code?

Try, txtBatchCV.Text For example
//Just for null
txtBatchCV.Text = (txtBatchCV.Text ?? "ALL").ToString();
//for both null and empty string
txtBatchCV.Text = string.IsNullOrEmpty(txtBatchCV.Text) ? "ALL": txtBatchCV.Text;

You could iterate through all the textboxes
foreach (var txt in form.Controls.OfType<TextBox>())
{
switch(txt.Id){
case "txtBatchCV":
// Do whatever you want for txtBatchCV e.g. check string.IsNullOrEmpy(txt.Text)
break;
}
}
I borrowed the above from here:
How do I loop through all textboxes and make them run corresponding actions from action dictionary?
In response to the comment I got from Tim, I've added a bit more code to explain what you could do. My code example was never meant to be a full solution.

TextBox.Text is never null, it will return "" then. If your methods return null you could use the null-coalescing operator:
string nullRepl = "ALL";
txtExternalCV.Text = Sqlrunclass.SplitSpec_External(part, pg) ?? nullRepl;
txtInternalCV.Text = Sqlrunclass.SplitSpec_Internal() ?? nullRepl;
txtABSCV.Text = Sqlrunclass.SplitSpec_cvABS() ?? nullRepl;
txtOilCV.Text = Sqlrunclass.SplitSpec_OilSeal() ?? nullRepl;
txtLocnCV.Text = Sqlrunclass.SplitInfo_Location() ?? nullRepl;
txtFitsCV.Text = Sqlrunclass.SplitInfo_Desc() ?? nullRepl;
txtHeightCV.Text = Sqlrunclass.SplitSpec_Height() ?? nullRepl;
txtDiameterCV.Text = Sqlrunclass.SplitSpec_Diameter() ?? nullRepl;
txtCirclitCV.Text = Sqlrunclass.SplitSpec_Circlit() ?? nullRepl;

For starters you could use string.IsNullOrEmpty(txtBatchCV.Text), it's a convevience method that basically does what you do in the if check.

You can atleast use one of these methods:
string.IsNullOrEmpty(txtBatchCV.Text)
or
string.IsNullOrWhitespace(txtBatchCV.Text)

I would try something like this:
void SetDefaultIfNull(TextBox txt, string defaultVal)
{
if (string.IsNullOrWhitespace(txt.Text))
txt.Text = defaultVal;
}
Then pass each textbox and the default to the method.

Related

Check if a column exists while reading a database in C#

In my database I made two different tables for objects, let's say OBJECT, and ORIGINAL_OBJECT(in French, in example it is Repere), the only difference between them is ORIGINAL_OBJECT has not any column where I save the modifies made.
I have a function that gets me all the fields :
public Repere Select_detail_repere(string query)
{
Repere det = null; ;
if (this.OpenConnection() == true)
{
IDataReader dataReader = ExecuteReader(query);
while (dataReader.Read())
{
det = new Repere();
det.Name = (dataReader["DET_NOM"] ?? string.Empty).ToString().Trim();
det.Modifies = dataReader["MODIFICATIONS"].ToString().Trim();
det.Profil = (dataReader["DET_PRF"] ?? string.Empty).ToString().Trim();
det.Matiere = (dataReader["DET_MAT"] ?? string.Empty).ToString().Trim();
det.GroupeProfil = (dataReader["DET_GRP_PRF"] ?? string.Empty).ToString().Trim();
det.Longueur = double.Parse(dataReader["LONGUEUR"].ToString().Trim());
det.Largeur = double.Parse(dataReader["DET_LARGE"].ToString().Trim());
det.Hauteur = double.Parse(dataReader["DET_HAUT"].ToString().Trim());
det.Poids = double.Parse(dataReader["DET_PDS"].ToString().Trim());
det.Angle1 = double.Parse(dataReader["ANG_AME_1"].ToString().Trim());
det.Angle2 = double.Parse(dataReader["ANG_AME_2"].ToString().Trim());
det.AngleAile1 = double.Parse(dataReader["ANG_AILE_1"].ToString().Trim());
det.AngleAile2 = double.Parse(dataReader["ANG_AILE_2"].ToString().Trim());
det.PercageString = (dataReader["PERCAGE"] ?? string.Empty).ToString().Trim();
det.ScribingString = (dataReader["SCRIBING"] ?? string.Empty).ToString().Trim();
det.Mark = (dataReader["MARK"] ?? string.Empty).ToString().Trim();
det.ContInt0 = (dataReader["CONT_INT"] ?? string.Empty).ToString().Trim();
det.ContExt0 = (dataReader["CONT_EXT"] ?? string.Empty).ToString().Trim();
det.Revision = (dataReader["REVISION"] ?? string.Empty).ToString().Trim();
}
this.CloseConnection();
}
return det;
}
I use the same function for both OBJECT and OBJECT_ORIGINAL.
But when I want to read my OBJECT_ORIGINAL, I meet an error that says the field doesn't exist (obviously).
I already met the same problem in other situations, as this function will only work if I use SELECT * (if I don't read all columns this will return an error).
Until now the only way I found to solve it is using try/catch (in the catch I will apply a default value, ID=-1 for example), but I feel as it is not a very correct solution, and looking for another way to do that.
You need to check if the column MODIFICATIONS exists in the datareader, as you don't know it on forehand.
In the documentation of Microsoft I found a method called GetSchemaTable.
It will give you a datatable that describes the column metadata. So you could check that table to see if there is a column with the name MODIFICATIONS.
I would put that check in a different method so it doesn't clutter the code in your while loop that much.
OR
You could check this question on StackOverflow Check for column name in a SqlDataReader object which has a shorter solution to your problem.
I think that's even a nicer and easier solution, but I found it (with a simple google search) after I had almost completed my answer above. So that's why I give you both solutions (and also to help you a little with the MS documentation, which I pointed to in my comment)
It would be helpful to give as the query you use as well but I think you can use IF COL_LENGTH('table_name','column_name') IS NOT NULL in your query.
You can use the mysql stored procedure and do the checking inside on it.
check it here.
check if column exists before ALTER TABLE -- mysql
This question can be quoted as "Duplicate", I found the answer on stack
public Repere Select_detail_repere(string query)
{
Repere det = null; ;
if (this.OpenConnection() == true)
{
IDataReader dataReader = ExecuteReader(query);
bool containsModification = CheckIfDataContains(dataReader, "MODIFICATIONS");
while (dataReader.Read())
{
det = new Repere();
det.Name = (dataReader["DET_NOM"] ?? string.Empty).ToString().Trim();
if(containsModification)
{
det.Modifies = dataReader["MODIFICATIONS"].ToString().Trim();
}
else
{
det.Modifies = "";
}
det.Profil = (dataReader["DET_PRF"] ?? string.Empty).ToString().Trim();
det.Matiere = (dataReader["DET_MAT"] ?? string.Empty).ToString().Trim();
...
}
this.CloseConnection();
}
return det;
}
public bool CheckIfDataContains(IDataReader dataReader,string columnName)
{
for (int i = 0; i < dataReader.FieldCount; i++)
{
if (dataReader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}

How To show blank datepicker when DB value is null

I've got a SQL DB column for DateTime Birthday on a customer object. The database allows that field to be null, but occasionally our users populate the data (from another system) with 1/1/1900.
I'd like to have my DatePicker field show nothing when the date in the DB is either null or DateTime.Parse("1900-01-01 00:00:00.000"). (It doesn't have to be fully blank, but can have the DatePicker field's standard default of " / / ".
I've been trying this:
dtBirthday.Value = customer.Birthday.HasValue ? customer.CustomerOptions.Birthday.Value : DateTime.Parse("1900-01-01 00:00:00.000");
That works fairly well for the null birthdays, but doesn't allow for the date in customer.Birthday actually being DateTime.Parse("1900-01-01 00:00:00.000").
Update
I did, in fact, google this, and attempted to use
var nullDate = DateTime.Parse("1900-01-01 00:00:00.000");
if (customer.Birthday.Value == nullDate)
{
dtBirthday.Format = eDateTimePickerFormat.Custom;
dtBirthday.CustomFormat = " ";
dtBirthday.Value = DateTime.FromOADate(0);
dtBirthday.Enabled = true;
}
else
{
dtBirthday.Format = eDateTimePickerFormat.Custom;
dtBirthday.CustomFormat = "M/d/yyyy";
dtBirthday.Value = customer.Birthday.Value;
dtBirthday.Enabled = true;
}
//dtBirthday.Value = customer.Birthday.HasValue ? customer.Birthday.Value : DateTime.Parse("1900-01-01 00:00:00.000");
if (customer.Anniversary.Value == nullDate)
{
dtAnniv.Format = eDateTimePickerFormat.Custom;
dtAnniv.CustomFormat = " ";
dtAnniv.Value = DateTime.FromOADate(0);
dtAnniv.Enabled = true;
}
else
{
dtAnniv.Format = eDateTimePickerFormat.Custom;
dtAnniv.CustomFormat = "MM/dd/yyyy";
dtAnniv.Value = customer.Anniversary.Value;
dtAnniv.Enabled = true;
}
//dtAnniv.Value = customer.Anniversary.HasValue ? customer.Anniversary.Value : DateTime.Parse("1900-01-01 00:00:00.000");
It does just about exactly what I want, except that the empty fields are completely disabled, even though I've specifically set them to enabled=true.
If I'm reading your question correctly, I think you want the text field to be empty when the birthday is actually null. Why not just populate it with an empty string:
txtBirthday.Value =
customer.Birthday.HasValue ?
customer.CustomerOptions.Birthday.Value.ToString() :
string.Empty;
After attempting several dozen different methods, none of which really did what I want, it occurred to me that I could just not set the value.
var nullDate = DateTime.Parse("1900-01-01 00:00:00.000");
if (customer.CustomerOptions.Birthday.HasValue && customer.CustomerOptions.Birthday.Value != nullDate)
{
dtBirthday.Value = customer.CustomerOptions.Birthday.Value;
}
if (customer.CustomerOptions.Anniversary.HasValue && customer.CustomerOptions.Anniversary.Value != nullDate)
{
dtAnniv.Value = customer.CustomerOptions.Anniversary.Value;
}

How to handle null values from SQLite DB with C#?

EDIT:
Thanks to everyone who replied! I appreciate all of your answers :)
So I have a class with the following constructor:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
//Paid = row.Field<int>("Paid");
//TotalBill = row.Field<int>("TotalBill");
}
Notice I have 2 of them commented out with /'s That's because if I don't they return null values even if I try ''row.Field([Whatever]).GetValueOrDefault()'', it still comes out null and my constructor returns null. I also have my DB set with default values so IDK what's wrong.
Anyone got a work around? :)
The DataRow class has a method that is called IsNull and that could receive the column name.
Just combine it with the conditional operator
Paid = row.IsNull("Paid") ? 0 : row.Field<int>("Paid");
the same is true for all other fields that could contain a null value.
Just check for null first and supply a default value:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
Paid = row.Field<int?>("Paid") ?? 0;
TotalBill = row.Field<int?>("TotalBill") ?? 0;
}
See the ?? Operator (C# Reference) page on MSDN for further information on the ?? operator.
You can simply use the Nullable type and GetValueOrDefault method or use null coalescing operator.
Paid = row.Field<int?>("Paid").GetValueOrDefault()
or
Paid = row.Field<int?>("Paid") ?? 0
In both cases Paid will have a value of 0, you can change if you want.
Create your own little function that does a simple check.
Along the lines of:
public integer GetNumber (object val)
{
if (IsNumeric (val))
{
return val;
} else
{
return 0;
}
}
I'm not fantastic with C#, but that should give you an idea. Sorry about formatting, I'm on a phone which doesn't help at all.

Don't have a nullReferenceException on XML Parsing

I have wrote a c# function in order to parse an XML Stream.
My XML can have several nodes.
Example :
<Stream>
<One>nnn</One>
<Two>iii</Two>
<Three>jjj</Three>
</Stream>
But sometimes, it is :
<Stream>
<Two>iii</Two>
</Stream>
Here is my c# code :
var XML = from item in XElement.Parse(strXMLStream).Descendants("Stream") select item;
string strOne = string.Empty;
string strTwo = string.Empty;
string strThree = string.Empty;
if ((item.Element("One").Value != "")
{
strOne = item.Element("One").Value;
}
if ((item.Element("Two").Value != "")
{
strTwo = item.Element("Two").Value;
}
if ((item.Element("Three").Value != "")
{
strThree = item.Element("Three").Value;
}
With this code, if my Stream is full ( Node On, Two and three), there's no problem! But, if my Stream has only the node "Two", I get a NullReferenceException.
Is there a way to avoid this exception (I cannot change my Stream).
Thanks a lot :)
You should check if item.Element("anything") is null before accessing it's Value property.
if (item.Element("Three") != null && item.Element("Three").Value != "")
You need to do:
if (item.Element("One") != null)
{
strOne = item.Element("One").Value;
}
.Element(String) returns null if an element of the name you requested does not exist.
Checking if value != "" is pointless, because all you are preventing is the reassignment of an empty string to the strOne variable, which is already an empty string. Also, if you really needed to do the empty string check, using String.IsNullOrEmpty(String) method is the preferred way.
Instead of accessing Value property (which raises NullReferenceException if element not exist, as you already know) cast elements to strings. You can use ?? to provide default value for non-existing elements:
string strOne = (string)item.Element("One") ?? String.Empty;
string strTwo = (string)item.Element("Two") ?? String.Empty;
string strThree = (string)item.Element("Three") ?? String.Empty;

Handling null objects in object setters

I am trying to use a nice near object setter, but have null issues.
My code right now:
var Result = new RefundReplyObject
{
AuthorisationNumber = reply.refundResponse.transactionDetails.authorisationNumber,
ChargeValue = reply.refundResponse.transactionDetails.totalAmount.amount,
Message = reply.refundResponse.transactionDetails.message,
ReconciliationReference = reply.refundResponse.transactionDetails.reconciliationReference,
SettlementDate = reply.refundResponse.transactionDetails.settlementDate,
Status = TransactionStatusToLocalModel(reply.refundResponse.transactionDetails.status),
TransactionReference = reply.refundResponse.transactionDetails.transactionReference
};
BUT ... 'totalAmount' might be null. So, I get errors.
Is there a neat way to handle this, so that if 'totalAmount' is null, then set chargevalue to zero?
How about a ternary operator, that checks to see if total amount is null. If it isn't, then use it's amount, otherwise 0.
ChargeValue = (reply.refundResponse.transactionDetails.totalAmount != null) ? reply.refundResponse.transactionDetails.totalAmount.amount : 0,
You could do, for example:
ChargeValue = reply.refundResponse.transactionDetails.totalAmount != null ? reply.refundResponse.transactionDetails.totalAmount.amount : 0
ternary operator to the rescue!
ChargeValue = totalAmount ? totalAmount.amount : 0;
Something like this?
ChargeValue = (null == reply.refundResponse.transactionDetails.totalAmount)
? 0
: reply.refundResponse.transactionDetails.totalAmount.amount
You're not going to be able to do it on the setter side of things since the exception is occuring before you even get there. You can get what you're after (and clean up your code substantially in the process) by doing something like this:
var trans = reply.refundResponse.transactionDetails;
var Result = new RefundReplyObject
{
AuthorisationNumber = trans.authorisationNumber,
ChargeValue = trans.totalAmount == null ? 0 : trans.totalAmount.amount,
Message = trans.message,
ReconciliationReference = trans.reconciliationReference,
SettlementDate = trans.settlementDate,
Status = TransactionStatusToLocalModeltrans.status),
TransactionReference = trans.transactionReference
};

Categories

Resources