Tuesday, September 2, 2008

More C# Learning Experiences

More C# Learning Experiences

I was trying to figure out how to create a modal dialog window in C#. (For those not familiar with the terminology: modal means that the user has to finish with this dialog window before he can go back to functions in the parent window.) I thought that this would be easy to find, but in the fast sea of C# documentation out there, it wasn't easy!

From the function that gets called when you select a menu option:
Form dlg = new Form();
dlg.ShowDialog();
If you specify dlg.Show(), you get a modeless dialog window instead.

A lot of the examples out there for dialog boxes assume that you are using the Visual Studio tools for building the dialog box. If you want a dialog box that is built dynamically from within your program, the examples are a bit harder to find.

// This is where we specify which lines to plot.
Form dlg = new Form();
// Create a panel
FlowLayoutPanel panel = new FlowLayoutPanel();
dlg.Controls.Add(panel);
// Add a button to the panel.
Button b = new Button();
b.Text = "OK";
panel.Controls.Add(b);
// Add a ListBox
ListBox box = new ListBox();
panel.Controls.Add(box);
dlg.ShowDialog();
You can't add a Button or ListBox control directly to a Form; you need a Panel object there first (much like Java's UI). A FlowLayoutPanel gives you a fair amount of control--or you can let it do most of the work for you, again, much like the equivalent in Java's UI.

CORRECTION: You can add controls, like Button directly to a Form. But all the controls end up on top of each other in the upper left corner of the Form, unless you tell them where to go.

I'll probably just keep expanding this as I learn things. You add a button click event driver like this:

b.Click += new EventHandler(this.bClick);


and the event handler is:

private void bClick(Object s, EventArgs e)
{
System.Console.WriteLine("hit the button");
}

No comments:

Post a Comment