Wednesday 7 May 2014

WPF - How to use FileOpenDialog, SaveFileDialog, PrintDialog

Unlike in Windows Forms, WPF doesn't have a FileOpenDialog component in the Controls toolkit.
But you can access the Dialogs classes from Microsoft.Win32 namespace.
A sample usage is as below:
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process open file dialog box results
if (result == true)
// Open document
string filename = dlg.FileName;

Similarly you can use other DialogBoxes from the namespace like:
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
System.Windows.Controls.PrintDialog dlg = new System.Windows.Controls.PrintDialog();

Tuesday 6 May 2014

C# - How to check if a column exists in a DataRow

It's a common requirement when you work with DataRows to check if a column exists. The next check would be if the column has a value which we will see afterwards in this post.

To check if a column exists:
dRow.Table.Columns["msisdn"] == null
The row doesn't contain a column property as such. Therefore you will have to get into the Parent table property to check into the columns in the row.

If the column doesn't exist,
dr["msisdn"] == null
will throw and error.

To check if a column has value and is not null value:
dr["msisdn"] == DBNull.Value
are used to check if a column has value