Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Issue accessing ListBox directly after data binding

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
US
I am trying to access a ListBox right after I data bind to it and am getting an error that says it is empty. I assume it doesn't do it right away and is done somewhere down the line because the ListBox has data when the form comes back.

In the following code the SelectList has data in it when I binds to the ListBox. But gives an error if you try to query it.

Code:
public List<StatementItem> SelectList { get; set; }

...

SelectList = (from DataRow dr in SelectStatements.Tables[0].Rows
                select new StatementItem
                {
                    Statement = (string)dr["Statement"],
                    StatementName = (string)dr["StatementName"],
                    DBStatementID = dr["DBStatementID"].ToString()
                }).ToList();

lbStatementNames.DisplayMember = "StatementName";
lbStatementNames.ValueMember = "DBStatementID";
lbStatementNames.DataSource = SelectList;

txtSelectStatement.Text = ((StatementItem)SelectList.First(x => x.DBStatementID == (string)lbStatementNames.Items[0])).Statement;

The error I get from the last statement is:

InvalidArgument=Value of '0' is not valid for 'index'.

if you look at the lbStatementNames.Items.Count, it is 0. But SelectList.Count = 5.

When the form comes back it has 5 items in it.

At which point can I query this ListBox after the data binding?

Thanks,

Tom
 
I also tried to set the selection to the 3rd item:
Code:
lbStatementNames.DisplayMember = "StatementName";
lbStatementNames.ValueMember = "DBStatementID";
lbStatementNames.DataSource = SelectList;

lbStatementNames.SelectedItem = 2;

I didn't get an error but the 1st item was selected. I assume that was because there were no items in the listbox yet.

I can't find anywhere where anyone talks about the point at which the object is populated or how to get it populate immediately.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top