1

I am building a C# application with ASP.Net Web Form having two dropdown list. One list is for selecting the hour and the other list is for selecting the minute. Once both dropdownlist are selected I would like to put them together to display as a single unit of time. For instance, if someone was to select 9 as the hour from dropdownlist1 and 25 as the minute from dropdownlist2, the two selections would store in a database as one unit of time 9:25 and could be selected from the database as a 9:25.

1 Answers1

0

I know it's a week late but since your question didn't get any attention, so..

I assume you already filled your dropdownlist controls, let's start to get their selected item values;

string hour = dropdownlist1.SelectedItem.Text;
string minute = dropdownlist2.SelectedItem.Text;

Now these hour and minutes strings will be probably 9 and 25. Since the situation we talk about is to get and save a time interval, it will be good to parse it to TimeSpan first which is exactly what this for in .NET Framework.

TimeSpan ts = TimeSpan.Parse(string.Format("{0}:{1}", hour, minute), 
                             CultureInfo.InvariantCulture);

With this operation, we will have a TimeSpan which has 9 hour and 25 minutes. And it seems as {09:25:00} in debugger.

If you use SQL Server, it has a time type which is mapped with TimeSpan in CLR data type. You can directly insert this type of data to your column.

using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
     cmd.CommandText = "insert into MyTable(myColumn) VALUES (@myValue)";
     cmd.Parameters.Add("@myValue", SqlDbType.Time).Value = ts;
     con.Open();
     cmd.ExecuteNonQuery();
}

Now, in your table you have a value from 00:00:00.0000000 to 23:59:59.9999999 range. When you get this value as a TimeSpan from your database, you can format it to see it as 9:25 as a textual representation.

string s = ts.ToString("h\\:mm"); // s will be 9:25

But remember, TimeSpan.ToString(string) overload came with .NET 4 version. If you use lower version, you can check this question;

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364