Reputation: 3030
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 overcome 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++;
}
}
Upvotes: 1
Views: 11637
Reputation: 14898
You could try using if(string.IsNullOrEmpty(hash1[i]))
or check for null prior to calling ToString()
.
if (hash[i] != null &&
hash[i].ToString() == "")
{
...
Upvotes: 1
Reputation: 351
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.
Upvotes: 0
Reputation: 378
From C# 6 and onwards you can use the Null-conditional operator ?.
if (hash[i]?.ToString() == "") { ...
Upvotes: 0
Reputation: 8356
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() + "'");
}
Upvotes: 0