Our app has a list of items displayed in a DataGridView. The first column is a DataGridViewCheckBoxColumn. We want our app to allow the user to click anywhere on the row as a way to select the CheckBox in the first column.
We find that if the user clicks directly on the CheckBox, selection/deselection works well. The same is true if the user clicks on the data in the other columns.
However, if the user clicks just to one side of the checkbox, we get strange behavior. The CheckBox in that row is not selected/deselected, but often another row is selected. To get a clearer picture of what is happening, you can check out my Short Video of the buggy behavior.
I tried setting some breakpoints in the code, for example, on our SelectionChanged handler, our CellClick handler and our CellValueChanged handler. I find these breakpoints are hit in the same pattern, regardless of whether I click on the CheckBox, just to one side of the checkbox or on the data in the other columns.
Has anyone seen behavior like this? Any ideas what may be going on? Is it a bug in the .NET DataGridView code, or is there something I should look for in our code?
Here is the relevant code, as requested (or you can download a ZIP file with the complete solution)...
From Form1.cs:
public Form1()
{
InitializeComponent();
dgsControl.SetUp();
}
From Form1.Designer.cs:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dgsControl = new DGSelection();
this.Controls.Add(this.dgsControl);
//
// dgsControl
//
this.dgsControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgsControl.Location = new System.Drawing.Point(3, 3);
this.dgsControl.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.dgsControl.Name = "dgsControl";
this.dgsControl.Size = new System.Drawing.Size(689, 325);
this.dgsControl.TabIndex = 0;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "DataGridView Demo";
}
From DGSelection.cs:
public partial class DGSelection : UserControl
{
#region Member variables
private class ListData
{
public string Option;
public string Description;
}
private static readonly List<ListData> TestData = new List<ListData>
{
new ListData { Option = "Option1", Description = "Description1" },
new ListData { Option = "Option2", Description = "Description2" },
new ListData { Option = "Option3", Description = "Description3" },
new ListData { Option = "Option4", Description = "Description4" }
};
public event EventHandler OptionsChanged;
#endregion
#region Constructor
public DGSelection()
{
InitializeComponent();
dgvTable.BackgroundColor = Color.DarkGray;
dgvTable.DefaultCellStyle.BackColor = Color.DarkGray;
dgvTable.DefaultCellStyle.ForeColor = Color.Black;
dgvTable.ColumnHeadersDefaultCellStyle.BackColor = Color.DarkGray;
dgvTable.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
dgvTable.GridColor = Color.DarkGray;
cbxCheckAll.BackColor = Color.DarkGray;
// Move label where it belongs (moved elsewhere in Designer for ease of editing).
lbl_empty.Top = Top + 5;
}
#endregion
#region Public Methods
public void SetUp()
{
dgvTable.Rows.Clear();
cbxCheckAll.Checked = false;
bool anyRows = TestData.Any();
lbl_empty.Visible = !anyRows;
cbxCheckAll.Visible = anyRows;
dgvTable.ColumnHeadersVisible = anyRows;
foreach (ListData ld in TestData)
{
dgvTable.Rows.Add(false, ld.Option, ld.Description);
}
}
#endregion
#region Event Handlers
private void DGSelection_SelectionChanged(object sender, EventArgs e)
{
dgvTable.ClearSelection();
}
private void cbxCheckAll_CheckedChanged(object sender, EventArgs e)
{
try
{
dgvTable.CellValueChanged -= DgvTableCellValueChanged;
bool checkAll = cbxCheckAll.Checked;
foreach (DataGridViewRow row in dgvTable.Rows)
row.Cells[0].Value = checkAll;
}
finally
{
dgvTable.CellValueChanged += DgvTableCellValueChanged;
}
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
private void DGSelection_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0)
return; // Ignore clicks in the header row
DataGridViewCell checkBoxCell = dgvTable.Rows[e.RowIndex].Cells[0];
checkBoxCell.Value = !(bool)checkBoxCell.Value;
}
private void DgvTableCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
try
{
cbxCheckAll.CheckedChanged -= cbxCheckAll_CheckedChanged;
cbxCheckAll.CheckedChanged -= cbxCheckAll_CheckedChanged;
// Not sure why, but sometimes subscribed twice
bool checkAll = dgvTable.Rows.Count > 0;
foreach (DataGridViewRow row in dgvTable.Rows)
checkAll &= row.Cells[0].Value.Equals(true);
cbxCheckAll.Checked = checkAll;
}
finally
{
cbxCheckAll.CheckedChanged += cbxCheckAll_CheckedChanged;
}
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
private void DGSelection_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dgvTable.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
#endregion
}
From DGSelection.Designer.cs:
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.dgvTable = new System.Windows.Forms.DataGridView();
this.colCheckboxes = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.colText1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colText2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.cbxCheckAll = new System.Windows.Forms.CheckBox();
this.lbl_empty = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgvTable)).BeginInit();
this.SuspendLayout();
//
// dgvTable
//
this.dgvTable.AllowUserToAddRows = false;
this.dgvTable.AllowUserToDeleteRows = false;
this.dgvTable.AllowUserToResizeColumns = false;
this.dgvTable.AllowUserToResizeRows = false;
this.dgvTable.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dgvTable.BackgroundColor = System.Drawing.SystemColors.Window;
this.dgvTable.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgvTable.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dgvTable.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.ControlDark;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.Padding = new System.Windows.Forms.Padding(3);
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvTable.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgvTable.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvTable.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colCheckboxes,
this.colText1,
this.colText2 });
this.dgvTable.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgvTable.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;
this.dgvTable.EnableHeadersVisualStyles = false;
this.dgvTable.Location = new System.Drawing.Point(0, 0);
this.dgvTable.Margin = new System.Windows.Forms.Padding(2);
this.dgvTable.MultiSelect = false;
this.dgvTable.Name = "dgvTable";
this.dgvTable.RowHeadersVisible = false;
this.dgvTable.RowTemplate.Height = 24;
this.dgvTable.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.dgvTable.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
this.dgvTable.Size = new System.Drawing.Size(484, 318);
this.dgvTable.TabIndex = 0;
this.dgvTable.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.DGSelection_CellClick);
this.dgvTable.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.DgvTableCellValueChanged);
this.dgvTable.CurrentCellDirtyStateChanged += new System.EventHandler(this.DGSelection_CurrentCellDirtyStateChanged);
this.dgvTable.SelectionChanged += new System.EventHandler(this.DGSelection_SelectionChanged);
//
// colCheckboxes
//
this.colCheckboxes.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.colCheckboxes.Frozen = true;
this.colCheckboxes.HeaderText = "";
this.colCheckboxes.Name = "colCheckboxes";
this.colCheckboxes.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colCheckboxes.Width = 30;
//
// colText1
//
this.colText1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.colText1.DefaultCellStyle = dataGridViewCellStyle2;
this.colText1.HeaderText = "Option";
this.colText1.Name = "colText1";
this.colText1.ReadOnly = true;
this.colText1.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colText1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
this.colText1.Width = 57;
//
// colText2
//
this.colText2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle3.Padding = new System.Windows.Forms.Padding(5, 0, 0, 0);
this.colText2.DefaultCellStyle = dataGridViewCellStyle3;
this.colText2.HeaderText = "Description";
this.colText2.Name = "colText2";
this.colText2.ReadOnly = true;
this.colText2.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.colText2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// cbxCheckAll
//
this.cbxCheckAll.AutoSize = true;
this.cbxCheckAll.BackColor = System.Drawing.SystemColors.ControlDark;
this.cbxCheckAll.Location = new System.Drawing.Point(8, 5);
this.cbxCheckAll.Margin = new System.Windows.Forms.Padding(2);
this.cbxCheckAll.Name = "cbxCheckAll";
this.cbxCheckAll.Size = new System.Drawing.Size(15, 14);
this.cbxCheckAll.TabIndex = 1;
this.cbxCheckAll.UseVisualStyleBackColor = false;
this.cbxCheckAll.CheckedChanged += new System.EventHandler(this.cbxCheckAll_CheckedChanged);
//
// lbl_empty
//
this.lbl_empty.Anchor = ((System.Windows.Forms.AnchorStyles)
(((System.Windows.Forms.AnchorStyles.Top |
System.Windows.Forms.AnchorStyles.Left) |
System.Windows.Forms.AnchorStyles.Right)));
this.lbl_empty.BackColor = System.Drawing.Color.Transparent;
this.lbl_empty.Location = new System.Drawing.Point(3, 25);
this.lbl_empty.Name = "lbl_empty";
this.lbl_empty.Size = new System.Drawing.Size(478, 44);
this.lbl_empty.TabIndex = 2;
this.lbl_empty.Text = "No data defined for the list";
this.lbl_empty.Visible = false;
//
// DGSelection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lbl_empty);
this.Controls.Add(this.cbxCheckAll);
this.Controls.Add(this.dgvTable);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "DGSelectionControl";
this.Size = new System.Drawing.Size(484, 318);
((System.ComponentModel.ISupportInitialize)(this.dgvTable)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
Is there something in our code which is causing this behavior? Or is it a bug in the implementation of DataGridView? I have reproduced this with both .NET Framework v.4.6 & v.4.8.
(Note: reposted from Microsoft Q&A Forum, since I got no responses there.)
I suggest these changes (tested with .Net Framework 4.8):
Don't use the CheckBox CheckedChanged event: it will interfere with the CellValueChanged event when it tries to change the Select All CheckBox state. Use the CellClick event instead.
This will also allow to get rid of all those add handler / remove handler things.
Call RefreshEdit() to update the state of the CheckBox Cell as soon as the Cell is clicked: this will update the CheckBox value immediately (this is the problem you're seeing when clicking inside the Cell's area instead of the CheckBox content: the control is not updated right away).
For more details, see the notes here:
Programmatically check a DataGridView CheckBox that was just unchecked
Remove that CommitEdit(DataGridViewDataErrorContexts.Commit);: if you need to update a value immediately, call the DataGridView.EndEdit() method instead (see those notes on this, too). It's more or less the same thing under the hood, but the name itself - EndEdit - makes its functionality much more understandable and it's easier to remember.
This is how it works now:
private void cbxCheckAll_Click(object sender, EventArgs e)
{
if (dgvTable.Rows.Count == 0) return;
try {
bool checkAll = cbxCheckAll.Checked;
foreach (DataGridViewRow row in dgvTable.Rows) {
row.Cells[0].Value = checkAll;
}
}
finally {
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
}
private void DGSelection_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0) return;
bool currentValue = (bool)dgvTable[0, e.RowIndex].Value;
dgvTable[0, e.RowIndex].Value = !currentValue;
}
private void DgvTableCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (!dgvTable.IsHandleCreated) return;
cbxCheckAll.Checked = dgvTable.Rows.OfType<DataGridViewRow>().All(r => (bool)r.Cells[0].Value == true);
dgvTable.BeginInvoke(new Action(() => dgvTable.RefreshEdit()));
OptionsChanged?.Invoke(this, EventArgs.Empty);
}
Related
I've inherited this project that someone started on a while back. It's made with DevExpress for Winforms. He already had a "welcome" page ready, with the "welkom" label and the "ik heb een afspraak" label (top of the 3 bottom ones). I've just started working on it today and can't seem to find out why my newly added Labelcontrols (the 2 bottom ones) aren't showing up when I launch the program/winforms.
Here's an image of how the designer looks:
Here's the Designer code page (Designer.cs file):
partial class Welcome
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.layoutCtrlMain = new DevExpress.XtraLayout.LayoutControl();
this.lblPickupRepair = new DevExpress.XtraEditors.LabelControl();
this.lblNoAppointment = new DevExpress.XtraEditors.LabelControl();
this.lblAppointment = new DevExpress.XtraEditors.LabelControl();
this.lblWelcome = new DevExpress.XtraEditors.LabelControl();
this.layoutMain = new DevExpress.XtraLayout.LayoutControlGroup();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.emptySpaceItem2 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem3 = new DevExpress.XtraLayout.EmptySpaceItem();
this.emptySpaceItem4 = new DevExpress.XtraLayout.EmptySpaceItem();
this.emptySpaceItem5 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem6 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.layoutCtrlMain)).BeginInit();
this.layoutCtrlMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.layoutMain)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
this.SuspendLayout();
//
// layoutCtrlMain
//
this.layoutCtrlMain.Controls.Add(this.lblPickupRepair);
this.layoutCtrlMain.Controls.Add(this.lblNoAppointment);
this.layoutCtrlMain.Controls.Add(this.lblAppointment);
this.layoutCtrlMain.Controls.Add(this.lblWelcome);
this.layoutCtrlMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutCtrlMain.Location = new System.Drawing.Point(0, 0);
this.layoutCtrlMain.Name = "layoutCtrlMain";
this.layoutCtrlMain.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(2218, 466, 859, 400);
this.layoutCtrlMain.Root = this.layoutMain;
this.layoutCtrlMain.Size = new System.Drawing.Size(1131, 427);
this.layoutCtrlMain.TabIndex = 0;
//
// lblPickupRepair
//
this.lblPickupRepair.Appearance.Font = new System.Drawing.Font("Tahoma", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblPickupRepair.Appearance.ForeColor = System.Drawing.Color.White;
this.lblPickupRepair.Appearance.Image = global::ESC.Intern.Custom.DigRecWF.Reception.Properties.Resources.Webp_net_resizeimage;
this.lblPickupRepair.Appearance.Options.UseFont = true;
this.lblPickupRepair.Appearance.Options.UseForeColor = true;
this.lblPickupRepair.Appearance.Options.UseImage = true;
this.lblPickupRepair.ImageAlignToText = DevExpress.XtraEditors.ImageAlignToText.LeftCenter;
this.lblPickupRepair.IndentBetweenImageAndText = 15;
this.lblPickupRepair.Location = new System.Drawing.Point(355, 309);
this.lblPickupRepair.Name = "lblPickupRepair";
this.lblPickupRepair.Size = new System.Drawing.Size(326, 49);
this.lblPickupRepair.StyleController = this.layoutCtrlMain;
this.lblPickupRepair.TabIndex = 8;
this.lblPickupRepair.Text = "Afhaling / herstelling";
//
// lblNoAppointment
//
this.lblNoAppointment.Appearance.Font = new System.Drawing.Font("Tahoma", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblNoAppointment.Appearance.ForeColor = System.Drawing.Color.White;
this.lblNoAppointment.Appearance.Image = global::ESC.Intern.Custom.DigRecWF.Reception.Properties.Resources.Webp_net_resizeimage;
this.lblNoAppointment.Appearance.Options.UseFont = true;
this.lblNoAppointment.Appearance.Options.UseForeColor = true;
this.lblNoAppointment.Appearance.Options.UseImage = true;
this.lblNoAppointment.ImageAlignToText = DevExpress.XtraEditors.ImageAlignToText.LeftCenter;
this.lblNoAppointment.IndentBetweenImageAndText = 15;
this.lblNoAppointment.Location = new System.Drawing.Point(355, 256);
this.lblNoAppointment.Name = "lblNoAppointment";
this.lblNoAppointment.Size = new System.Drawing.Size(331, 49);
this.lblNoAppointment.StyleController = this.layoutCtrlMain;
this.lblNoAppointment.TabIndex = 7;
this.lblNoAppointment.Text = "Ik heb geen afspraak";
this.lblNoAppointment.Click += new System.EventHandler(this.lblNoAppointment_Click);
//
// lblAppointment
//
this.lblAppointment.Appearance.Font = new System.Drawing.Font("Tahoma", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblAppointment.Appearance.ForeColor = System.Drawing.Color.White;
this.lblAppointment.Appearance.Image = global::ESC.Intern.Custom.DigRecWF.Reception.Properties.Resources.Webp_net_resizeimage;
this.lblAppointment.Appearance.Options.UseFont = true;
this.lblAppointment.Appearance.Options.UseForeColor = true;
this.lblAppointment.Appearance.Options.UseImage = true;
this.lblAppointment.ImageAlignToText = DevExpress.XtraEditors.ImageAlignToText.LeftCenter;
this.lblAppointment.IndentBetweenImageAndText = 15;
this.lblAppointment.Location = new System.Drawing.Point(355, 203);
this.lblAppointment.Name = "lblAppointment";
this.lblAppointment.Size = new System.Drawing.Size(315, 49);
this.lblAppointment.StyleController = this.layoutCtrlMain;
this.lblAppointment.TabIndex = 5;
this.lblAppointment.Text = "Ik heb een afspraak";
this.lblAppointment.Click += new System.EventHandler(this.lblAppointment_Click);
//
// lblWelcome
//
this.lblWelcome.Appearance.Font = new System.Drawing.Font("Arial Narrow", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblWelcome.Appearance.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.lblWelcome.Appearance.Options.UseFont = true;
this.lblWelcome.Appearance.Options.UseForeColor = true;
this.lblWelcome.Location = new System.Drawing.Point(290, 70);
this.lblWelcome.Name = "lblWelcome";
this.lblWelcome.Size = new System.Drawing.Size(396, 75);
this.lblWelcome.StyleController = this.layoutCtrlMain;
this.lblWelcome.TabIndex = 4;
this.lblWelcome.Text = "Welkom bij ESC!";
//
// layoutMain
//
this.layoutMain.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
this.layoutMain.GroupBordersVisible = false;
this.layoutMain.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.emptySpaceItem1,
this.emptySpaceItem2,
this.layoutControlItem1,
this.emptySpaceItem3,
this.emptySpaceItem4,
this.emptySpaceItem5,
this.layoutControlItem2,
this.emptySpaceItem6,
this.layoutControlItem4,
this.layoutControlItem3});
this.layoutMain.Name = "Root";
this.layoutMain.Size = new System.Drawing.Size(1131, 427);
this.layoutMain.TextVisible = false;
//
// emptySpaceItem1
//
this.emptySpaceItem1.AllowHotTrack = false;
this.emptySpaceItem1.Location = new System.Drawing.Point(678, 0);
this.emptySpaceItem1.MinSize = new System.Drawing.Size(104, 24);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(433, 407);
this.emptySpaceItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// emptySpaceItem2
//
this.emptySpaceItem2.AllowHotTrack = false;
this.emptySpaceItem2.Location = new System.Drawing.Point(0, 0);
this.emptySpaceItem2.Name = "emptySpaceItem2";
this.emptySpaceItem2.Size = new System.Drawing.Size(278, 407);
this.emptySpaceItem2.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.lblWelcome;
this.layoutControlItem1.Location = new System.Drawing.Point(278, 58);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(400, 79);
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextVisible = false;
//
// emptySpaceItem3
//
this.emptySpaceItem3.AllowHotTrack = false;
this.emptySpaceItem3.Location = new System.Drawing.Point(278, 350);
this.emptySpaceItem3.MinSize = new System.Drawing.Size(104, 24);
this.emptySpaceItem3.Name = "emptySpaceItem3";
this.emptySpaceItem3.Size = new System.Drawing.Size(400, 57);
this.emptySpaceItem3.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.emptySpaceItem3.TextSize = new System.Drawing.Size(0, 0);
//
// emptySpaceItem4
//
this.emptySpaceItem4.AllowHotTrack = false;
this.emptySpaceItem4.Location = new System.Drawing.Point(278, 0);
this.emptySpaceItem4.Name = "emptySpaceItem4";
this.emptySpaceItem4.Size = new System.Drawing.Size(400, 58);
this.emptySpaceItem4.TextSize = new System.Drawing.Size(0, 0);
//
// emptySpaceItem5
//
this.emptySpaceItem5.AllowHotTrack = false;
this.emptySpaceItem5.Location = new System.Drawing.Point(278, 137);
this.emptySpaceItem5.Name = "emptySpaceItem5";
this.emptySpaceItem5.Size = new System.Drawing.Size(400, 54);
this.emptySpaceItem5.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.lblAppointment;
this.layoutControlItem2.Location = new System.Drawing.Point(343, 191);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(335, 53);
this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem2.TextVisible = false;
//
// emptySpaceItem6
//
this.emptySpaceItem6.AllowHotTrack = false;
this.emptySpaceItem6.Location = new System.Drawing.Point(278, 191);
this.emptySpaceItem6.Name = "emptySpaceItem6";
this.emptySpaceItem6.Size = new System.Drawing.Size(65, 159);
this.emptySpaceItem6.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.lblNoAppointment;
this.layoutControlItem4.Location = new System.Drawing.Point(343, 244);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(335, 53);
this.layoutControlItem4.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem4.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.lblPickupRepair;
this.layoutControlItem3.Location = new System.Drawing.Point(343, 297);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(335, 53);
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextVisible = false;
//
// Welcome
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(1131, 427);
this.Controls.Add(this.layoutCtrlMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "Welcome";
this.Text = "Form1";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.Welcome_Load);
this.Shown += new System.EventHandler(this.Welcome_Shown);
((System.ComponentModel.ISupportInitialize)(this.layoutCtrlMain)).EndInit();
this.layoutCtrlMain.ResumeLayout(false);
this.layoutCtrlMain.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.layoutMain)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutCtrlMain;
private DevExpress.XtraLayout.LayoutControlGroup layoutMain;
private DevExpress.XtraEditors.LabelControl lblWelcome;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem4;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem5;
private DevExpress.XtraEditors.LabelControl lblAppointment;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem6;
private DevExpress.XtraEditors.LabelControl lblPickupRepair;
private DevExpress.XtraEditors.LabelControl lblNoAppointment;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem2;
}
}
And here's the code page (.cs file):
public partial class Welcome : BaseForm
{
public Welcome(int timeoutIntervalInSeconds, Controller controller) : base(timeoutIntervalInSeconds, controller)
{
InitializeComponent();
if (!_controller.IsDesignMode)
{
}
_controller.SetDesignMode(layoutCtrlMain);
}
private void Welcome_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
{
if (!_controller.IsDesignMode) return;
_controller.SaveLayout(layoutCtrlMain, Enums.LayoutType.Welcome);
}
private void lblAppointment_Click(object sender, EventArgs e)
{
_controller.OpenAppointments();
Close();
}
private void lblNoAppointment_Click(object sender, EventArgs e)
{
_controller.OpenAppointments();
Close();
}
private void Welcome_Load(object sender, EventArgs e)
{
_controller.LoadLayout(layoutCtrlMain, Enums.LayoutType.Welcome);
layoutCtrlMain.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
layoutCtrlMain.LookAndFeel.UseDefaultLookAndFeel = false;
layoutCtrlMain.OptionsView.ShareLookAndFeelWithChildren = false;
layoutCtrlMain.OptionsView.EnableTransparentBackColor = true;
layoutCtrlMain.Root.AppearanceGroup.BackColor = System.Drawing.Color.Transparent;
layoutCtrlMain.Root.AppearanceGroup.Options.UseBackColor = true;
var sharepath = _controller.GetSharePath(Enums.LayoutType.Welcome);
var backFile = Path.Combine(_controller.GetSharePath(LayoutType.Welcome), "background.png");
if (File.Exists(backFile)) layoutCtrlMain.BackgroundImage = Image.FromFile(backFile);
//throws them out of the main layoutgroup...
/*layoutControlItem4.RestoreFromCustomization();
layoutControlItem3.RestoreFromCustomization();*/
}
private void Welcome_Shown(object sender, EventArgs e)
{
LoadMenuDisplayed();
}
private void LoadMenuDisplayed()
{
//var sharepath = _controller.GetSharePath(LayoutType.Appointment);
//((System.ComponentModel.ISupportInitialize)(this.layoutCtrlMain)).BeginInit();
//flpMain.SuspendLayout();
//flpMain.Controls.Clear();
//layoutCtrlMain.SuspendLayout();
//var itemFont = new Font("Arial", 18F, FontStyle.Bold);
//var fontService = _controller.GetContainer().Resolve(typeof(ILayoutService), "") as ILayoutService;
//if (fontService != null)
//{
// var fontResponse = fontService.GetFontLayout(LayoutType.Appointment_Font_EmployeeNameButton);
// if (fontResponse.IsSuccess) itemFont = fontResponse.GetValue().Font;
//}
//var firstBtn = new MyHoverButton();
//int counter = 0;
//foreach (var item in response.Values)
//{
// if (counter >= 20) break; //we only show 20 employees max
// var btn = new MyHoverButton();
// btn.TextLocation = TextLocation.Bottom;
// btn.ItemText = item.FullName;
// btn.ItemValue = item.ID;
// btn.ItemFont = itemFont;
// if (item.ID > 0)
// {
// var medwImg = Path.Combine(_controller.GetSharePath(LayoutType.Appointment), "Medewerkers", "contact_" + item.ID + ".jpg");
// if (File.Exists(medwImg))
// {
// btn.NormalImage = Image.FromFile(medwImg);
// //btn.HoverImage = Image.FromFile(medwImg);
// }
// else
// {
// }
// }
// btn.BorderStyle = BorderStyle.None;
// //btn.Width = flpMain.Size.Width / 5;
// //btn.Height = flpMain.Size.Height / 4;
// btn.ItemClicked += Btn_Click;
// flpMain.Controls.Add(btn);
// counter++;
//}
//layoutCtrlMain.ResumeLayout();
//flpMain.ResumeLayout();
//((System.ComponentModel.ISupportInitialize)(this.layoutCtrlMain)).EndInit();
}
}
}
I'm not familiar with DevExpress so maybe I'm forgetting something somewhere?
I'm not familiar with DevExpress so maybe I'm forgetting something
somewhere?
I believe that you did not forget anything, because new labels already visible in the designer. There must be a very simple key to this riddle.
Comment out this line in the Welcome_Load method:
_controller.LoadLayout(layoutCtrlMain, Enums.LayoutType.Welcome);
If this helps, then newly added labels are not shown because the previously saved layout do not contain them.
To fix this problem and keep the _controller.LoadLayout code line uncommented, find the file where your _controller saves the layout and delete it.
I have created menu dynamically.But I don't know how to handle events of menu Item.Please Let me know if anyone have solution.Thanks in Advance.
ToolStripMenuItem master,transaction,report,exit;
private void Menu1_Load(object sender, EventArgs e)
{
master = new ToolStripMenuItem("Master");
menuStrip1.Items.Add(master);
master.DropDownItems.Add("Party Master");
master.DropDownItems.Add("Item Master");
master.DropDownItems.Add("Tax Master");
master.Click += MenuClicked;
transaction = new ToolStripMenuItem("Transaction");
menuStrip1.Items.Add(transaction);
transaction.DropDownItems.Add("Inward");
transaction.DropDownItems.Add("Inoice");
transaction.DropDownItems.Add("Daily Expense");
report = new ToolStripMenuItem("Report");
menuStrip1.Items.Add(report);
report.DropDownItems.Add("Master Report");
report.DropDownItems.Add("Transaction Report");
report.DropDownItems.Add("Daily Expense Report");
exit = new ToolStripMenuItem("Exit");
menuStrip1.Items.Add(exit);
}
private void MenuClicked(object o,EventArgs e)
{
if ((((ToolStripMenuItem)o).Text) == "Party Master")
{
Master.PartyMaster p = new Master.PartyMaster();
p.Show();
}
}`
`// Master
master.DropDownItems.
AddRange(new System.Windows.Forms.ToolStripItem[]
{
partyMaster,
itemMaster,
taxMaster
}
);
master.Name = "Master";
master.Size = new System.Drawing.Size(125, 20);
master.Text = "Master";
master.Click += new System.EventHandler(master_Click);
// Party Master
partyMaster.Name = "PartyMaster";
partyMaster.Size = new System.Drawing.Size(152, 22);
partyMaster.Text = "PartyMaster";
partyMaster.Click += new System.EventHandler(partyMaster_Click);
// Item Master
itemMaster.Name = "ItemMaster";
itemMaster.Size = new System.Drawing.Size(152, 22);
itemMaster.Text = "ItemMaster";
// Tax Master
taxMaster.Name = "TaxMaster";
taxMaster.Size = new System.Drawing.Size(152, 22);
taxMaster.Text = "TaxMaster"; //`
Or more dynamically with List and for loop.
List<ToolStripMenuItem> items = new List<ToolStripMenuItems>();
And loop to add more items to the Menu
ToolStripMenuItem item = new ToolStripMenuItem();
items.Add(item);
item.Click += new EventHandler(MenuClicked); // if you want to stick with only one function
Try add your dropdown items this way:
ToolStripItem partyMaster = new ToolStripMenuItem() { Text = "Party Master" };
partyMaster.Click += MenuClicked;
ToolStripItem itemMaster = new ToolStripMenuItem() { Text = "Item Master" };
itemMaster.Click += MenuClicked;
ToolStripItem taxMaster = new ToolStripMenuItem() { Text = "Tax Master" };
taxMaster.Click += MenuClicked;
master.DropDownItems.Add(partyMaster);
master.DropDownItems.Add(itemMaster);
master.DropDownItems.Add(taxMaster);
I am a beginner in C#, so please bear with me. I have a form where I have a tab control, this tab control has 3 tabs. I am trying to show a form with each tab page. I am able to show a form on the first tab, but for some reason, the other two tabs do not load the forms. This is the code that I have. Am I doing something wrong? Do you have any suggestions?
private void MainTab_Load(object sender, EventArgs e)
{
HomeScreen fHome = new HomeScreen();
fHome.TopLevel = false;
fHome.Visible = true;
fHome.FormBorderStyle = FormBorderStyle.None;
fHome.Dock = DockStyle.Fill;
MainOptions.TabPages[0].Controls.Add(fHome);
}
private void CustomerTab_Click(object sender, EventArgs e)
{
CustomerScreen fCustomer = new CustomerScreen();
fCustomer.TopLevel = false;
fCustomer.Visible = true;
fCustomer.FormBorderStyle = FormBorderStyle.None;
fCustomer.Dock = DockStyle.Fill;
MainOptions.TabPages[1].Controls.Add(fCustomer);
}
edit:
More:
Also, in the tabcontrol- InitializeComponent I have the following
// HomeTab
//
this.HomeTab.Location = new System.Drawing.Point(4, 22);
this.HomeTab.Name = "HomeTab";
this.HomeTab.Size = new System.Drawing.Size(677, 452);
this.HomeTab.TabIndex = 0;
this.HomeTab.Text = "Home";
this.HomeTab.UseVisualStyleBackColor = true;
this.HomeTab.Click += new System.EventHandler(this.MainTab_Load);
//
// CustomerTab
//
this.CustomerTab.Location = new System.Drawing.Point(4, 22);
this.CustomerTab.Name = "CustomerTab";
this.CustomerTab.Padding = new System.Windows.Forms.Padding(3);
this.CustomerTab.Size = new System.Drawing.Size(677, 452);
this.CustomerTab.TabIndex = 1;
this.CustomerTab.Text = "Customer";
this.CustomerTab.UseVisualStyleBackColor = true;
this.CustomerTab.Click += new System.EventHandler(this.CustomerTab_Click);
I think you're just missing the Show() method...
And a suggestion: I don't know what kind of Pattern you're using, but as a beginner, you should declare your forms outside those methods, as a variable within the class scope, so you can access then later...
private HomeScreen fHome = new HomeScreen();
private CustomerScreen fCustomer = new CustomerScreen();
private void MainTab_Load(object sender, EventArgs e)
{
fHome.TopLevel = false;
fHome.Visible = true;
fHome.FormBorderStyle = FormBorderStyle.None;
fHome.Dock = DockStyle.Fill;
MainOptions.TabPages[0].Controls.Add(fHome);
fHome.Show(); // add this
}
private void CustomerTab_Click(object sender, EventArgs e)
{
fCustomer.TopLevel = false;
fCustomer.Visible = true;
fCustomer.FormBorderStyle = FormBorderStyle.None;
fCustomer.Dock = DockStyle.Fill;
MainOptions.TabPages[1].Controls.Add(fCustomer);
fCustomer.Show(); // add this
}
There's a lot to improve here, but that's a start.
Is there any way to add a System.Windows.Controls.TextBox to GroupBox controls in C#?
I tried the following but it doesn't show up in the groupbox:
public System.Windows.Controls.TextBox textBox6 = new System.Windows.Controls.TextBox();
public System.Windows.Controls.TextBox textBox7 = new System.Windows.Controls.TextBox();
public ElementHost sumtext = new ElementHost();
public ElementHost loctext = new ElementHost();
private void Form1_Load(object sender, EventArgs e)
{
textBox6.Name = "Summary";
textBox7.Name = "Location";
textBox6.FontFamily = new System.Windows.Media.FontFamily("Microsoft Sans Serif");
textBox6.FontSize = 12;
textBox6.SpellCheck.IsEnabled = true;
textBox7.FontFamily = new System.Windows.Media.FontFamily("Microsoft Sans Serif");
textBox7.FontSize = 12;
textBox7.SpellCheck.IsEnabled = true;
groupBox4.Controls.Add(sumtext);
sumtext.Dock = DockStyle.None;
sumtext.Width = 246;
sumtext.Height = 35;
sumtext.Child = textBox6;
sumtext.Location = new Point(3, 33);
sumtext.Visible = true;
sumtext.Enabled = false;
groupBox4.Controls.Add(sumtext);
groupBox4.Controls.Add(loctext);
loctext.Dock = DockStyle.None;
loctext.Width = 246;
loctext.Height = 35;
loctext.Child = textBox7;
loctext.Location = new Point(3, 90);
loctext.Visible = true;
loctext.Enabled = false;
this.Controls.Add(sumtext);
this.Controls.Add(loctext);
}
I need to use System.Windows.Controls.TextBox rather than Form.TextBox as I need it for spell check.
Any help would be greatly appreciated!
I changed the Enabled property of the sumtext, and removed the other box to shorten it:
This code works for me:
public Form1()
{
this.Load += new System.EventHandler(this.Form1_Load);
}
public System.Windows.Controls.TextBox textBox6 = new System.Windows.Controls.TextBox();
public ElementHost sumtext = new ElementHost();
private System.Windows.Forms.GroupBox groupBox4;
private void Form1_Load(object sender, EventArgs e)
{
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.SuspendLayout();
//
// groupBox4
//
this.groupBox4.Location = new System.Drawing.Point(57, 63);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(591, 238);
this.groupBox4.TabIndex = 0;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "groupBox1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(706, 478);
this.Controls.Add(this.groupBox4);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
textBox6.Name = "Summary";
textBox6.FontFamily = new System.Windows.Media.FontFamily("Microsoft Sans Serif");
textBox6.FontSize = 12;
textBox6.SpellCheck.IsEnabled = true;
groupBox4.Controls.Add(sumtext);
sumtext.Dock = DockStyle.None;
sumtext.Width = 246;
sumtext.Height = 35;
sumtext.Child = textBox6;
sumtext.Location = new Point(3, 33);
sumtext.Visible = true;
sumtext.Enabled = true;
groupBox4.Controls.Add(sumtext);
}
Is this code actually getting called? Has groupbox 4 been added to the form yet?
You should not be adding your ElementHost controls to your Form AND your GroupBox, it appears to be confusing .NET. Keeping your original code exactly as-is but commenting out these two lines makes it work:
//this.Controls.Add(sumtext);
//this.Controls.Add(loctext);
Also... I don't think it's hurting anything, but you don't need to do this twice:
//groupBox4.Controls.Add(sumtext);
Hello I'm currently creating an application which has the need to add server IP addresses to it, as there is no InputBox function in C# I'm trying to complete this using forms, but am very new to the language so not 100% as to what I should do.
At the moment I have my main form and a form which will act as my inputbox which wants to hide on load. Then when the user clicks on the add IP Address on the main form I wish to open up the secondary form and return the IP address entered into a text box on the secondary form.
So how would I go about doing this? Or is there any better ways to achieve similar results?
In your main form, add an event handler for the event Click of button Add Ip Address. In the event handler, do something similar as the code below:
private string m_ipAddress;
private void OnAddIPAddressClicked(object sender, EventArgs e)
{
using(SetIPAddressForm form = new SetIPAddressForm())
{
if (form.ShowDialog() == DialogResult.OK)
{
//Create a property in SetIPAddressForm to return the input of user.
m_ipAddress = form.IPAddress;
}
}
}
Edit: Add another example to fit with manemawanna comment.
private void btnAddServer_Click(object sender, EventArgs e)
{
string ipAdd;
using(Input form = new Input())
{
if (form.ShowDialog() == DialogResult.OK)
{
//Create a property in SetIPAddressForm to return the input of user.
ipAdd = form.IPAddress;
}
}
}
In your Input form, add a property:
public class Input : Form
{
public string IPAddress
{
get { return txtInput.Text; }
}
private void btnInput_Click(object sender, EventArgs e)
{
//Do some validation for the text in txtInput to be sure the ip is well-formated.
if(ip_well_formated)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
}
You could just use the VB InputBox...
Add reference to Microsoft.VisualBasic
string result = Microsoft.VisualBasic.Interaction.InputBox("Title","text", "", 10, 20);
I've needed this feature, too. Here's my code; it auto-centers and sizes to fit the prompt. The public method creates a dialog and returns the user's input, or null if they cancel.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Utilities
{
public class InputBox
{
#region Interface
public static string ShowDialog(string prompt, string title, string defaultValue = null, int? xPos = null, int? yPos = null)
{
InputBoxDialog form = new InputBoxDialog(prompt, title, defaultValue, xPos, yPos);
DialogResult result = form.ShowDialog();
if (result == DialogResult.Cancel)
return null;
else
return form.Value;
}
#endregion
#region Auxiliary class
private class InputBoxDialog: Form
{
public string Value { get { return _txtInput.Text; } }
private Label _lblPrompt;
private TextBox _txtInput;
private Button _btnOk;
private Button _btnCancel;
#region Constructor
public InputBoxDialog(string prompt, string title, string defaultValue = null, int? xPos = null, int? yPos = null)
{
if (xPos == null && yPos == null)
{
StartPosition = FormStartPosition.CenterParent;
}
else
{
StartPosition = FormStartPosition.Manual;
if (xPos == null) xPos = (Screen.PrimaryScreen.WorkingArea.Width - Width ) >> 1;
if (yPos == null) yPos = (Screen.PrimaryScreen.WorkingArea.Height - Height) >> 1;
Location = new Point(xPos.Value, yPos.Value);
}
InitializeComponent();
if (title == null) title = Application.ProductName;
Text = title;
_lblPrompt.Text = prompt;
Graphics graphics = CreateGraphics();
_lblPrompt.Size = graphics.MeasureString(prompt, _lblPrompt.Font).ToSize();
int promptWidth = _lblPrompt.Size.Width;
int promptHeight = _lblPrompt.Size.Height;
_txtInput.Location = new Point(8, 30 + promptHeight);
int inputWidth = promptWidth < 206 ? 206 : promptWidth;
_txtInput.Size = new Size(inputWidth, 21);
_txtInput.Text = defaultValue;
_txtInput.SelectAll();
_txtInput.Focus();
Height = 125 + promptHeight;
Width = inputWidth + 23;
_btnOk.Location = new Point(8, 60 + promptHeight);
_btnOk.Size = new Size(100, 26);
_btnCancel.Location = new Point(114, 60 + promptHeight);
_btnCancel.Size = new Size(100, 26);
return;
}
#endregion
#region Methods
protected void InitializeComponent()
{
_lblPrompt = new Label();
_lblPrompt.Location = new Point(12, 9);
_lblPrompt.TabIndex = 0;
_lblPrompt.BackColor = Color.Transparent;
_txtInput = new TextBox();
_txtInput.Size = new Size(156, 20);
_txtInput.TabIndex = 1;
_btnOk = new Button();
_btnOk.TabIndex = 2;
_btnOk.Size = new Size(75, 26);
_btnOk.Text = "&OK";
_btnOk.DialogResult = DialogResult.OK;
_btnCancel = new Button();
_btnCancel.TabIndex = 3;
_btnCancel.Size = new Size(75, 26);
_btnCancel.Text = "&Cancel";
_btnCancel.DialogResult = DialogResult.Cancel;
AcceptButton = _btnOk;
CancelButton = _btnCancel;
Controls.Add(_lblPrompt);
Controls.Add(_txtInput);
Controls.Add(_btnOk);
Controls.Add(_btnCancel);
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = false;
MinimizeBox = false;
return;
}
#endregion
}
#endregion
}
}
Add a button in main form.
Create a form with textbox for ip address. (lets say it IPAddressForm)
Add click event handler for that button.
In the event handler, create an instance of IPAddressForm and call showdialog method of IPAddressForm.
Store the ip address in some class variable.
If the showdialog result is ok, read the class variable from main form (simplest way is to declare the field as public)
Looks like Francis has the correct idea which is what I would have suggested. However, just to add to this I would probably suggest using a MaskedTextBox instead of a basic TextBox and add the IP Address format as the Mask.
You can create your special messagebox. I created my messagebox for getting database information like below. And when the messagebox open, application stop during you click any button in related messagebox.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
namespace Palmaris_Installation
{
public class efexBox
{
public static string ShowDialog()
{
PopUpDatabase form = new PopUpDatabase();
DialogResult result = form.ShowDialog();
if (result == DialogResult.Cancel)
return null;
else
{
if (form.ValueAuthentication == "SQL Server Authentication")
return form.Valueservername + "?" + form.ValueAuthentication + "?" + form.ValueUsername + "?" + form.ValuePassword;
else
return form.Valueservername + "?" + form.ValueAuthentication + "?" + "" + "?" + "";
}
}
public partial class PopUpDatabase : Form
{
public PopUpDatabase()
{
InitializeComponent();
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable table = instance.GetDataSources();
foreach (DataRow row in table.Rows)
{
cmbServerName.Items.Add(row[0] + "\\" + row[1]);
}
cmbAuthentication.Items.Add("Windows Authentication");
cmbAuthentication.Items.Add("SQL Server Authentication");
return;
}
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.cmbServerName = new System.Windows.Forms.ComboBox();
this.cmbAuthentication = new System.Windows.Forms.ComboBox();
this.txtUserName = new System.Windows.Forms.TextBox();
this.txtPassword = new System.Windows.Forms.TextBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnConnect);
this.groupBox1.Controls.Add(this.btnCancel);
this.groupBox1.Controls.Add(this.txtPassword);
this.groupBox1.Controls.Add(this.txtUserName);
this.groupBox1.Controls.Add(this.cmbAuthentication);
this.groupBox1.Controls.Add(this.cmbServerName);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(348, 198);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Database Configration";
this.groupBox1.BackColor = Color.Gray;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(50, 46);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(69, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Server Name";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(50, 73);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(75, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Authentication";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(50, 101);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 0;
this.label3.Text = "User Name";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(50, 127);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Password";
//
// cmbServerName
//
this.cmbServerName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbServerName.FormattingEnabled = true;
this.cmbServerName.Location = new System.Drawing.Point(140, 43);
this.cmbServerName.Name = "cmbServerName";
this.cmbServerName.Size = new System.Drawing.Size(185, 21);
this.cmbServerName.TabIndex = 1;
//
// cmbAuthentication
//
this.cmbAuthentication.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbAuthentication.FormattingEnabled = true;
this.cmbAuthentication.Location = new System.Drawing.Point(140, 70);
this.cmbAuthentication.Name = "cmbAuthentication";
this.cmbAuthentication.Size = new System.Drawing.Size(185, 21);
this.cmbAuthentication.TabIndex = 1;
this.cmbAuthentication.SelectedIndexChanged += new System.EventHandler(this.cmbAuthentication_SelectedIndexChanged);
//
// txtUserName
//
this.txtUserName.Location = new System.Drawing.Point(140, 98);
this.txtUserName.Name = "txtUserName";
this.txtUserName.Size = new System.Drawing.Size(185, 20);
this.txtUserName.TabIndex = 2;
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(140, 124);
this.txtPassword.Name = "txtPassword";
this.txtPassword.Size = new System.Drawing.Size(185, 20);
this.txtPassword.TabIndex = 2;
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(250, 163);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.DialogResult = DialogResult.Cancel;
//
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(140, 163);
this.btnConnect.Name = "btnConnect";
this.btnConnect.Size = new System.Drawing.Size(75, 23);
this.btnConnect.TabIndex = 3;
this.btnConnect.Text = "Connect";
this.btnConnect.UseVisualStyleBackColor = true;
this.btnConnect.DialogResult = DialogResult.OK;
//
// PopUpDatabase
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(348, 198);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "PopUpDatabase";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "::: Database Configration :::";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtPassword;
private System.Windows.Forms.TextBox txtUserName;
private System.Windows.Forms.ComboBox cmbAuthentication;
private System.Windows.Forms.ComboBox cmbServerName;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Button btnCancel;
public string ValueUsername { get { return txtUserName.Text; } }
public string ValuePassword { get { return txtPassword.Text; } }
public string Valueservername { get { return cmbServerName.SelectedItem.ToString(); } }
public string ValueAuthentication { get { return cmbAuthentication.SelectedItem.ToString(); } }
private void cmbAuthentication_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbAuthentication.SelectedIndex == 1)
{
txtUserName.Enabled = true;
txtPassword.Enabled = true;
}
else
{
txtUserName.Enabled = false;
txtPassword.Enabled = false;
}
}
}
}
}
and in your main application call like :
string[] strPopUp = efexBox.ShowDialog().Split('?');