tags:

views:

577

answers:

3

I've got a wpf listbox that is bound to a datatable. At some times, I want to programmaticly change the selection of the listbox. I know the text of the item I want to select. But it doesn't work to set the listbox1.SelectedItem to the text I want because the type of the SelectedItem is System.Data.DataRowView.

If I have the text I want to select and the DataRow that I want to select, what is the easiest way select the associated row in the list box?

A: 

Search through your DataSet and find the appropriate DataRow. Then set SelectedItem to that DataRow.

HTH, Kent

Kent Boogaart
A: 

The ListBox control (both in Forms and WebControls) has a SelectedValue property that:

"Gets the value of the selected item in the list control, or selects the item in the list control that contains the specified value."

You could use this to select the item based on it's value, typically a unique key.

More info from MSDN:

System.Windows.Forms.ListControl.SelectedValue

System.Web.UI.WebControls.ListControl.SelectedValue

sgriffinusa
I didn't say it in the question, but the question was tagged wpf.
epotter
+1  A: 

If you know the text, then it would be:

ListBox1.SelectedValue = ListBox1.Items.FindByText("Two").Value;

You can also use the SelectedIndex property to set the selected value by 0-based index.

Nick
listBox1.Items doesn't have a FindByText method.
epotter