Full view of ComboBox drop-down list components in C# 3.0

By default in C# 3.0 ComboBox controls don’t provide support for showing drop-down list items if they exceed the width of their parent ComboBox, like this one:

Cropped ComboBox

Cropped ComboBox

This is annoying because users cannot read properly the information. To solve that problem, all we have to do is derive the ComboBox class and override the DropDown event as follows:

public class ComboBoxEx : ComboBox
{
	public ComboBoxEx()
		: base()
	{
		DropDown += new EventHandler(event_DropDown);
	}
 
	void event_DropDown(object sender, EventArgs e)
	{
		try
		{
			ComboBox comboBox = (ComboBox)sender; // Catch the combo firing this event
			int width = comboBox.Width; // Current width for ComboBox
			Graphics g = comboBox.CreateGraphics(); // Get graphics for ComboBox
			Font font = comboBox.Font; // Doesn't change original font
 
			//checks if a scrollbar will be displayed.
			int vertScrollBarWidth;
			if (comboBox.Items.Count > comboBox.MaxDropDownItems)
			}
				//If yes, then get its width to adjust the size of the drop down list.
				vertScrollBarWidth = SystemInformation.VerticalScrollBarWidth;
			}
			else
			{
				//Otherwise set to 0
				vertScrollBarWidth = 0;
			}
			//Loop through list items and check size of each items.
			//set the width of the drop down list to the width of the largest item.
			int newWidth;
			foreach (string s in comboBox.Items)
			{
				if (s != null)
				{
					newWidth = (int)g.MeasureString(s.Trim(), font).Width + vertScrollBarWidth;
					if (width < newWidth)
						width = newWidth;
				}
			}
			// Finally, adjust the new width
			comboBox.DropDownWidth = width;
		}
		catch {  }
	}   
}

The following picture shows the results of using the above control instead of the default one:

Non Cropped ComboBox

Non Cropped ComboBox

  • Share/Bookmark

Controlling the commands executed with xp_cmdshell on SQL Server 2005

SQL Server has a special extended stored procedure called xp_cmdshell. This procedure has a lot of power: it allows to execute any command line code on the machine hosting the SQL Server.

Imagine you want to list all the files on C: on the SQL Server Windows host: you could write a T-SQL statement like this one:

EXECUTE master..xp_cmdshell 'dir c:'

This stored procedure, however, is a very dangerous one, as it would allow to execute harmful code. This is the reason why it’s disabled by default. Even when enabled, only users on the sysadmin role can use it.

If you ever need some users the ability to run only some specific commands with xp_cmdshell, you can use the method I’ll explain below, making use of the EXECUTE AS modifier of the stored procedure definitions in T-SQL.

Read the rest of this entry »

  • Share/Bookmark