How to Handle the Hashtable null value?
I have a problem while checking a hashtable value. In the code below I am storing 60 values in the hashtable "hash". One of the values is (or can be) Null. I am checking each entry against its corresponding entry in hashtable "hash1", to see if they match each other. If they don't match I want to check if the value in "hash" is Null, but I can't catch it - it's falling through the 'else' part). How can I over开发者_开发知识库come this problem?
if (hash[j].ToString() == "")
{
NotAnswerQuestionCount++;
}
My Code:
int ctAnsCount=0, flAnsCount=0,NotAnswerQuestionCount=0;
SqlDataAdapter sda =
new SqlDataAdapter("select quesno,[Key] from Answerkey" ,con);
DataSet ds = new DataSet();
sda.Fill(ds);
Hashtable hash = new Hashtable();
for (int i = 0; i < 60; i++)
{
hash[i+1] = ResultsListBox.Items[i].ToString();
}
Hashtable hash1 = new Hashtable();
for (int i = 0; i < 60; i++)
{
hash1[i+1] = ds.Tables[0].Rows[i][1].ToString();
}
for (int j = 1; j <=60; j++)
{
if (hash[j].ToString() != hash1[j].ToString())
{
if (hash[j].ToString() == "")
{
NotAnswerQuestionCount++;
}
//else
flAnsCount++;
}
else
{
ctAnsCount++;
}
}
Test for hash1[i] != null prior to using ToString().
You could try using if(string.IsNullOrEmpty(hash1[i]))
or check for null prior to calling ToString()
.
if (hash[i] != null &&
hash[i].ToString() == "")
{
...
I don't think you mean null, I think you mean empty. You're checking the contents of 'hash', which looks like it is filled from a ListBox, but AFAIK a ListBox item can't be null. Also, you're checking to see if it matches the empty string (""
).
How do you know that you have an empty string in the ListBox? Try Trim-ing the value before you check it (i.e. if (hash[j].ToString().Trim() == "")
to catch empty strings as well as strings that only contain whitespace. Alternatively output the contents of each ListBox item to debug, bracketed by a delimiter, to check that you've actually got, like so:
foreach (Object o in ResultsListBox.Items) {
Debug.WriteLine("'" + o.ToString() + "'");
}
From C# 6 and onwards you can use the Null-conditional operator ?.
if (hash[i]?.ToString() == "") { ...
If you want to check whether a Hash Object is null or size is zero.
I think you can do like this
if (hash!= null || hash.Keys.Count==0) { blah }
Thank you.
精彩评论