ComboBox Tasten-Auswahl bei Zeit-Werten
Frank Dzaebel, erstellt am: 30.06.2005, zuletzt geändert: 30.06.2005
Kategorie:Winform-Controls, .NET-Version:1.1 

Der folgende Code beschreibt eine Implementations-Möglichkeit für eine ComboBox mit Zeitwerten (06:00 - 24:00), deren Wert-Auswahl über Tasten erfolgen soll und zum Beispiel bei der Taste 9 direkt den Wert 09:00 auswählt.

const int MinHour= 6;
const int MaxHour=24;
Regex regex;

private void Form1_Load(object sender, System.EventArgs e)
{
  StringBuilder sbPattern = new StringBuilder("^(");
  for (int h=MinHour; h<=MaxHour; h++)
  { 
    comboBox1.Items.Add((h*100).ToString("0:00"));
    sbPattern.AppendFormat("({0})|", h.ToString("0"));
  }
  regex = new Regex(sbPattern.Remove(sbPattern.Length-1,
    1).ToString()+")", RegexOptions.Compiled);
  comboBox1.SelectedIndex=0;
}

bool TextChangedAllowed = true;
string oldComboText="";

private void comboBox1_TextChanged(object sender, System.EventArgs e)
{
  if (!TextChangedAllowed) {TextChangedAllowed=true;return;}
  TextChangedAllowed=false; int hour;
  string val = regex.Match(comboBox1.Text).Value;
  if (val=="") {ResetComboText(val); return;}
  hour = int.Parse(val);
  if (hour>0 && hour<=MaxHour/10) {TextChangedAllowed=true; return;}
  while (hour>MaxHour) hour/=10;
  if (hour<MinHour || hour>MaxHour) {ResetComboText(val); return;}
  comboBox1.SelectedIndex = hour-MinHour;
  if (comboBox1.Text.Length>0)
    if (comboBox1.Text[0]=='1' || comboBox1.Text[0]=='2') 
      comboBox1.SelectionStart=1;
  TextChangedAllowed=true; oldComboText=comboBox1.Text;
}

private void ResetComboText(string val)
{
  if (comboBox1.Text.Length>0)
  {
    string s = comboBox1.Text.Substring(0,1);
    if (val=="" && comboBox1.Text.Length>=1)
      if (IsAllowedPreNumber(s))
        oldComboText=regex.Match(s+"0").Value+":00";
  }
  TextChangedAllowed=false; 
  comboBox1.Text = oldComboText;
}
private bool IsAllowedPreNumber(string num)
{
  if (num == "") return false;
  string match = regex.Match(num+"0").Value;
  return (match.Length>1);
}