Showing posts with label c# - ListBox. Show all posts
Showing posts with label c# - ListBox. Show all posts

Tuesday, September 4, 2018

C# - How to add items to ListBox from DataTable

DataTable table = new DataTable();

table.Columns.Add( new DataColumn( "Text", typeof( string ) ) );
table.Columns.Add( new DataColumn( "Number", typeof( double ) ) );

table.Rows.Add( new object[] { "Value 1", 1 } );
table.Rows.Add( new object[] { "Value 2", 2 } );
table.Rows.Add( new object[] { "Value 3", 3 } );

listBox1.DisplayMember = "Text";
listBox1.DataSource = table;
Output:

C# - How to add items to ListBox

listBox1.Items.Clear();

listBox1.Items.Add( "One" );
listBox1.Items.Add( "Two" );
listBox1.Items.Add( "Three" );
, or (from array):
listBox1.Items.Clear();
   
String[] sArray = { "One", "Two", "Three" };
listBox1.Items.AddRange( sArray );
, or
listBox1.DataSource = new string[] { "One", "Two", "Three" };
Output: