Dan
Dan

Reputation: 4663

Why is count not accurate?

Here's the idea: the user can add items and they populate in a listbox control. If the user has no items, they should not be able to submit the form. However, I add an artificial item when there are no items using:

if (ds.Tables[0].Rows.Count == 0)
{
    lstItems.Items.Insert(0, "No items have been added.");
}
else
{
    lstItems.DataSource = ds;
    lstItems.DataTextField = "ItemInfo";
    lstItems.DataValueField = "Item_ID";
    lstItems.DataBind();
}

Later, I want to ensure there are items before submitting, but the DataSet (ds) is not available in that function/context. To resolve this, I declared a global variable (public int) within the class that could be referenced:

public int numItems = 0;

Then set it like so:

numItems = ds.Tables[0].Rows.Count;

That way it wouldn't be thrown off by the one artificial record I inserted in lstItems. However, this isn't working. The value remains 0, even thought the above conditional statement evaluates correctly indicating that the row count is not 0. What am I doing wrong? Is there a better way of doing this? I considered using:

if (lstItems.Items.Count < 1)
{
    // allow submission
}

But the problem with this is that it hits off my artificial item:

lstItems.Items.Insert(0, "No items have been added.");

So what is the best way to check if there are any user-created items in the list?

Upvotes: 1

Views: 156

Answers (2)

MIke
MIke

Reputation: 140

When the user adds an item, remove your default item from the list. Then instead of basing validation on the count of items using a global, you can then base it on whether or not your artificial item exists in the list.

Upvotes: 0

Karthik Ganesan
Karthik Ganesan

Reputation: 4222

numItems is initialized to 0 on postbacks you wont be able to get the value in button click...

use some thing like this

ViewState["count"] =  ds.Tables[0].Rows.Count;

and check the count on button click

if(Convert.ToInt32(ViewState["count"]) > 0)
{
// your logic
}

Upvotes: 2

Related Questions