Tuesday, July 20, 2010

Concise Code to Enable/Disable WinForm Controls

Let's say you have a check box (cb1)  on a form that enables a text box (txt1)  and disables a listbox (lst1).  You can write a statement that shows this dependency on 2 lines:

  txt1.Enabled = cb1.Checked;
  lst1.Enabled = !cb1.Checked;

This works fine. However, we repeat the reference to the check box state twice.
There is a way to write the above statements on the same line:

   lst1.Enabled = !(txt1.Enabled = cb1.Checked);

Looks simple when you get it right. But it took me a few minutes to figure it out.

Friday, July 16, 2010

Examine Columns in ASP.NET Dynamic Data MetaTable

This is how you get access to all columns in a MetaTable that serves as a data source to your controls like a DetailsView or a GridView. Dynamic Data generates the following code for each ASP.NET page by default:


   protected MetaTable table;

   protected void Page_Load(object sender, EventArgs e)
   {
       table = DetailsDataSource.GetTable();
       Title = table.DisplayName;
   }
The MetaTable class has a Columns property that returns a collection of MetaColumns for the table. This allows us to enumerate through the collection and check for any custom attributes on table columns:
    
   foreach (MetaColumn column in table.Columns)
   {
      if (column.Attributes.OfType<MyCustomAttribute>().Count() > 0)
          ......
      }
   }

This is based on a tip found at this blog.

Thursday, July 8, 2010

Reverse .NET SortedList

 This post shows how you could reverse a SortedList in C# by its keys:

SortedList<string, string> strlist = new SortedList<string, string>();
strlist.Add("f3", "xxx");
strlist.Add("f1", "ccc");
strlist.Add("f2", "aaa");

foreach (KeyValuePair<string, string> kvp in strlist)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}           

Console.WriteLine("reverse the list");
IEnumerable<KeyValuePair<string, string>> revList = strlist.Reverse();
foreach (KeyValuePair<string, string> kvp in revList)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}