.NET     Console.WriteLine( "All Things .NET" );
.NET Nerd Blog Home
5.10.2002

 

Simple DropDown List



I am such a newbie to the controls in .NET that I thought I'd write down a few thoughts on the differences between WebForms and WinForms version of a drop-down list.

WinForms ComboBox class.

adapter.Fill( ds ); // fill some datasource
cbNames.DataSource = ds.Tables[0];
cbNames.DisplayMember = "T1USERNAME";
cbNames.ValueMember = "T1LOGINID";

Then to get the data out when a selection is made..

DataRowView drv = (DataRowView)cbNames.SelectedItem;
MessageBox.Show( drv["T1LOGINID"].ToString() );

When storing items in the WinForms combobox, you add objects instead of strings like old school. A visual representation of the object is displayed in the combobox at runtime. The content representation is specified by DisplayMember - this value will be used as the "property" to retrieve from the stored object. If this property is not set, ToString will be used.

Use SelectedItem to retrieve the object representing the current collection. Cast it back to whatever you know it to be, then get at the data you want.

WebForms DropDownList class
DropDownList is the server control for the <option> HTML element. This works somewhat simliar to the ComboBox WinForms control but has a few notable differences.


adapter.Fill( ds );
list1.DataSource = ds.Tables[0];
list1.DataTextField = "T1NAME";
list1.DataValueField = "T1NID";
list1.DataBind();

Then pull out the data with...

lblText.Text = "You selected ID " + list1.SelectedItem.Value +
", text is " + list1.SelectedItem.Text;


Since the control mimcs the OPTION element, it really only handles TEXT and VALUE pairs, so you use the DataTextField and DataValueField accordingly.

Then when you pull out the data for the selected item, it's just those two properties available on the System.Web.UI.Controls.ListItem class.



Comments: Post a Comment

Powered by Blogger