I'll assume the field is a datetime
or date
field. If the field is varchar
it should be parsed to datetime
or date
in the SQL query.
There's no need to convert dates to strings, or even add items one by one. You can use data binding to bind directly to the DataTable.
Windows Forms
Data binding combo boxesis described in How to: Bind a Windows Forms ComboBox or ListBox Control to Data
You can also use the FormatString
property to specify how the control should display the dates, eg ::
//Use local short date format
cmbStatementDate.FormatString = "d";
//or hard-coded short format
// cmbStatementDate.FormatString = "MM-dd-YYYY";
cmbStatementDate.DisplayMember = "statement_date";
cmbStatementDate.DataSource=dt;
The best place to specify the FormatString and DisplayMember
is the form designer itself though, not the code-behind file. This makes it a lot easier to localization and display formats.
Data binding means there's no need to redraw the combobox each time a new item is added either. The entire combo is redrawn only after all data is loaded.
It's also possible to pull control properties from settings or resource files. This would allow someone to localize an application simply by creating a new settings or resources file.
In general, localization, globalization and data binding are baked into .NET since 2002. You can create an application just once and easily localize it for different markes without formatting strings by hand.
You can read about data binding in general in :
A bit of warning
Don't use the data binding order shown in the documentation :
cmbStatementDate.DataSource=dt;
cmbStatementDate.DisplayMember = "statement_date";
This would repaint the control twice if possible, using the original DisplayMember
value.
WPF
Data binding and format strings work in WPF too, and are probably even easier to use. Without using data binding, one could create the formatted combobox with :
<ComboBox x:Name="cmbStatementDate"
DisplayMemberPath="statement_date" ItemStringFormat="d" />
or
<ComboBox x:Name="cmbStatementDate"
DisplayMemberPath="statement_date" ItemStringFormat="dd-MM-yyyy" />
And load the data with :
cmbStatementDate.ItemsSource=dt1;
This code looks like data binding and yet it isn't.
With data binding, the combo can bind to properties in the codebehind or a ViewModel class, eg :
<ComboBox x:Name="cmbStatementDate"
DisplayMemberPath="statement_date"
ItemStringFormat="dd-MM-yyyy"
ItemsSource="{Binding Path=MyDateData}"
SelectedValue="{Binding Path=SelectedDate}" />
In this case MyDateData
and SelectedDate
refer to properties in the codebehind or ViewModel.
Data Binding in WPF is described in Data Binding Overview