using System;
using System.Windows.Forms;
namespace ExtensionMethods
{
///
/// Add extensions to
///
public static class ComboBoxExtensions
{
///
/// Indicates whether the content of the specified is null or an string
///
///
/// . True: ComboBox is empty. False: ComboBox is not empty
public static bool IsEmpty(this ComboBox cb)
{
return String.IsNullOrEmpty(cb.Text);
}
///
/// Indicates whether the content of the specified is not null and not an string
///
///
/// . True: ComboBox is not empty. False: ComboBox is empty
public static bool IsNotEmpty(this ComboBox cb)
{
return !String.IsNullOrEmpty(cb.Text);
}
///
/// Creates a that mirrors this .
///
///
/// with same size and content as the
public static TextBox GetMirrorTextbox(this ComboBox cb)
{
TextBox textBox = null;
// Search for already existing TextBox
if (cb.Parent != null)
{
Control[] x = cb.Parent.Controls.Find("txt" + cb.Name, false);
if (x.Length > 0)
{
textBox = (TextBox)x[0];
return textBox;
}
}
// Generate a new TextBox
textBox = new TextBox();
textBox.Location = cb.Location;
textBox.Size = cb.Size;
textBox.Name = "txt" + cb.Name;
/*// Copy events
CopyEventHandlers ceh = new CopyEventHandlers();
ceh.GetHandlersFrom(cb).CopyTo(textBox);*/
// Copy attributes
textBox.BackColor = cb.BackColor;
cb.BackColorChanged += new EventHandler((object sender, EventArgs e) => { textBox.BackColor = ((ComboBox)sender).BackColor; });
textBox.ForeColor = cb.ForeColor;
cb.ForeColorChanged += new EventHandler((object sender, EventArgs e) => { textBox.ForeColor = ((ComboBox)sender).ForeColor; });
textBox.Font = cb.Font;
cb.FontChanged += new EventHandler((object sender, EventArgs e) => { textBox.Font = ((ComboBox)sender).Font; });
// Copy text
textBox.Text = cb.Text;
EventHandler eventHandler = new EventHandler((object sender, EventArgs e) => { textBox.Text = ((ComboBox)sender).Text; });
cb.TextChanged += eventHandler;
cb.SelectedIndexChanged += eventHandler;
if (cb.Parent != null)
cb.Parent.Controls.Add(textBox);
return textBox;
}
///
/// Simulates a property for by creating a new with same size, location and content.
/// Then one of both is hidden and the other shown.
///
///
/// . True: Show ; False: Show
public static void ReadOnly(this ComboBox cb, bool readOnly)
{
TextBox textBox = cb.GetMirrorTextbox();
textBox.ReadOnly = true;
textBox.Cursor = Cursors.Arrow;
textBox.Visible = readOnly;
cb.Visible = !readOnly;
cb.Enabled = !readOnly;
}
///
/// Clears all text from the
///
///
public static void Clear(this ComboBox cb)
{
cb.Text = String.Empty;
}
}
}