Creating an Inputbox in C# using forms - c#

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('?');

Related

How to take a snapshot with Ozeski SDK USB Camera?

I'm quite newbie in programming, but triyng to run my first app in VS2019, C# .NET. I want to take a snapshop from my USB microscope. I've found OZEKI SDK library and I'm able to connect and view image from microscope. Ozeki has a tutorial on youtube:
https://www.youtube.com/watch?v=xjMAfMAix9c
and their website,
https://www.camera-sdk.com/p_6553-how-to-take-a-picture-snapshot-and-save-it-as-.jpg-in-c-.html
but when I tried to run app, I got message:
" images.save(curentpath)" object does not contain a definition for 'save' and no accesible...."
Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Ozeki.Media;
using Ozeki.Camera;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
private DrawingImageProvider _imageProvider;
private MediaConnector _connector;
private VideoViewerWF _videoViewerWf;
private SnapshotHandler _snapshotHandler;
private IWebCamera _webCamera;
public Form1()
{
InitializeComponent();
_imageProvider = new DrawingImageProvider();
_connector = new MediaConnector();
_snapshotHandler = new SnapshotHandler();
_videoViewerWf = new VideoViewerWF();
SetVideoViewer();
}
private void SetVideoViewer()
{
CameraBox.Controls.Add(_videoViewerWf);
_videoViewerWf.Size = new Size(260, 180);
_videoViewerWf.BackColor = Color.Black;
_videoViewerWf.TabStop = false;
_videoViewerWf.Location = new Point(14, 19);
_videoViewerWf.Name = "_videoViewerWf";
}
private void button_Connect_Click(object sender, EventArgs e)
{
_webCamera = new WebCamera();
if (_webCamera != null)
{
_connector.Connect(_webCamera.VideoChannel, _imageProvider);
_connector.Connect(_webCamera.VideoChannel,_snapshotHandler);
_videoViewerWf.SetImageProvider(_imageProvider);
_webCamera.Start();
_videoViewerWf.Start();
}
}
private void button_SaveTo_Click(object sender, EventArgs e)
{
var result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
TextBox_SaveTo.Text = folderBrowserDialog1.SelectedPath;
}
private void Btn_Snapshot_Click(object sender, EventArgs e)
{
var path = TextBox_SaveTo.Text;
CreateSnapShot(path);
}
private void CreateSnapShot(string path)
{
var date = DateTime.Now.Year + "y-" + DateTime.Now.Month + "m-" + DateTime.Now.Day + "d-" +
DateTime.Now.Hour + "h-" + DateTime.Now.Minute + "m-" + DateTime.Now.Second + "s";
string currentpath;
if (String.IsNullOrEmpty(path))
currentpath = date + ".jpg";
else
currentpath = path + "\\" + date + ".jpg";
var snapShotImage = _snapshotHandler.TakeSnapshot().ToImage();
snapShotImage.Save(currentpath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
and Designer:
namespace WindowsFormsApp3
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button_Connect = new System.Windows.Forms.Button();
this.CameraBox = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.TextBox_SaveTo = new System.Windows.Forms.TextBox();
this.Btn_Snapshot = new System.Windows.Forms.Button();
this.button_SaveTo1 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button_Connect);
this.groupBox1.Location = new System.Drawing.Point(10, 10);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(120, 60);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Connect";
//
// button_Connect
//
this.button_Connect.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
this.button_Connect.ForeColor = System.Drawing.Color.Black;
this.button_Connect.Location = new System.Drawing.Point(10, 20);
this.button_Connect.Name = "button_Connect";
this.button_Connect.Size = new System.Drawing.Size(100, 25);
this.button_Connect.TabIndex = 6;
this.button_Connect.Text = "Connect";
this.button_Connect.UseVisualStyleBackColor = true;
this.button_Connect.Click += new System.EventHandler(this.button_Connect_Click);
//
// CameraBox
//
this.CameraBox.Location = new System.Drawing.Point(10, 80);
this.CameraBox.Name = "CameraBox";
this.CameraBox.Size = new System.Drawing.Size(285, 210);
this.CameraBox.TabIndex = 3;
this.CameraBox.TabStop = false;
this.CameraBox.Text = "Live camera ";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.TextBox_SaveTo);
this.groupBox2.Controls.Add(this.Btn_Snapshot);
this.groupBox2.Controls.Add(this.button_SaveTo1);
this.groupBox2.Location = new System.Drawing.Point(10, 300);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(285, 100);
this.groupBox2.TabIndex = 37;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Snapshot";
//
// TextBox_SaveTo
//
this.TextBox_SaveTo.Location = new System.Drawing.Point(119, 63);
this.TextBox_SaveTo.Name = "TextBox_SaveTo";
this.TextBox_SaveTo.Size = new System.Drawing.Size(160, 20);
this.TextBox_SaveTo.TabIndex = 35;
this.TextBox_SaveTo.Text = "C:\\Users\\user\\Documents\\Visual Studio 2012\\Projects\\03_Onvif_Network_Video_Record" +
"er\\03_Onvif_Network_Video_Recorder\\bin\\Debug";
//
// Btn_Snapshot
//
this.Btn_Snapshot.Location = new System.Drawing.Point(10, 20);
this.Btn_Snapshot.Name = "Btn_Snapshot";
this.Btn_Snapshot.Size = new System.Drawing.Size(100, 25);
this.Btn_Snapshot.TabIndex = 36;
this.Btn_Snapshot.Text = "Take a snapshot";
this.Btn_Snapshot.UseVisualStyleBackColor = true;
this.Btn_Snapshot.Click += new System.EventHandler(this.Btn_Snapshot_Click);
//
// button_SaveTo1
//
this.button_SaveTo1.Location = new System.Drawing.Point(10, 60);
this.button_SaveTo1.Name = "button_SaveTo1";
this.button_SaveTo1.Size = new System.Drawing.Size(100, 25);
this.button_SaveTo1.TabIndex = 34;
this.button_SaveTo1.Text = "Save to:";
this.button_SaveTo1.UseVisualStyleBackColor = true;
this.button_SaveTo1.Click += new System.EventHandler(this.button_SaveTo_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(309, 414);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.CameraBox);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Network Video Recorder Snapshot";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button_Connect;
private System.Windows.Forms.GroupBox CameraBox;
private System.Windows.Forms.TextBox TextBox_SaveTo;
private System.Windows.Forms.Button button_SaveTo1;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.Button Btn_Snapshot;
private System.Windows.Forms.GroupBox groupBox2;
}
}
Thanks in advance for any help.
OK, I did it. Change:
var snapShotImage = _snapshotHandler.TakeSnapshot().ToImage();
to
var snapShotImage = _snapShot.TakeSnapshot().ToImage() as System.Drawing.Image;

DataGridView CheckBox selection bug

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);
}

DevExpress Winforms: why aren't my newly added Labelcontrols showing up?

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.

Why does Visual Studio 2017 keep changing my public static statements to "public" after I change any aspect of any object on a form in C#

I've posted my code. Every single time I change anything on my this form in my Windows Forms App in C#, it changes my "public static" changes at the end to just "public" and then it adds "this." to every single reference to them. My code seems to run fine after I edit it again, but this is really annoying. I just wanted to make sure I'm not missing something or taking a poor approach to this.
The reason I am using public static statements is because I am modifying some Textboxes and a DataGridView object on my main form from other forms - i.e. looking up customer info from a database in one form and then entering the data on the main form to write up an order, and taking shopping cart information from a WebBrowser control on one form and putting it into a DataGridView object on another form. If this isn't how to accomplish populating forms from another form please tell me how and be as specific as possible as I am quite new to C#. Sorry if I've posted too much code - this is almost everything from my form1.cs file and I didn't know what (if anything) that I have here is causing the problem. The relevant "public static" statements are at the end.
(AFTER I WROTE THIS - I looked up another thread where someone said that forms are supposed to be a "specific instantiation" and that is why the developer environment keeps taking out the "static"). That being the case... HELP!! I do not understand how to change the values on one form from another form and I absolutely need to do so. - this code works, but I guess it's bad practice? - Completely lost and need very specific instructions to make this work)
Thanks in advance!!!
namespace WindowsFormsApp1
{
public partial class frmMain
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.cmdSendEmail = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdLookup = new System.Windows.Forms.Button();
this.txtTransactionNumber = new System.Windows.Forms.TextBox();
this.cmdEdit = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.cmdBrowse = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.cmdCustomer = new System.Windows.Forms.Button();
this.txtNotes = new System.Windows.Forms.TextBox();
txtZip = new System.Windows.Forms.TextBox();
txtCountry = new System.Windows.Forms.TextBox();
txtState = new System.Windows.Forms.TextBox();
txtCity = new System.Windows.Forms.TextBox();
txtAddress = new System.Windows.Forms.TextBox();
txtName = new System.Windows.Forms.TextBox();
txtPayPalEmail = new System.Windows.Forms.TextBox();
txtEmail = new System.Windows.Forms.TextBox();
txtPhone = new System.Windows.Forms.TextBox();
txtLast = new System.Windows.Forms.TextBox();
txtFirst = new System.Windows.Forms.TextBox();
grdOrderItems = new System.Windows.Forms.DataGridView();
this.Qty = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Description = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.UnitPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ExtPrice = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.SCode = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Options1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Options2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.lblSubTotal = new System.Windows.Forms.Label();
this.lblTotal = new System.Windows.Forms.Label();
this.txtTax = new System.Windows.Forms.TextBox();
this.txtShipping = new System.Windows.Forms.TextBox();
this.txtShippingMethod = new System.Windows.Forms.TextBox();
this.cmdTaxLookup = new System.Windows.Forms.Button();
this.lstShipping = new System.Windows.Forms.ListBox();
this.cmdBrowser = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.cmdSendRequest = new System.Windows.Forms.Button();
this.cmdClear = new System.Windows.Forms.Button();
this.cmdSave = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.cmdSavePrintEmail = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(grdOrderItems)).BeginInit();
this.groupBox3.SuspendLayout();
this.groupBox4.SuspendLayout();
this.SuspendLayout();
//
// cmdLookup
//
this.cmdLookup.Location = new System.Drawing.Point(88, 15);
this.cmdLookup.Name = "cmdLookup";
this.cmdLookup.Size = new System.Drawing.Size(197, 33);
this.cmdLookup.TabIndex = 3;
this.cmdLookup.Text = "Look up order to attach request to";
this.cmdLookup.UseVisualStyleBackColor = true;
//
// txtTransactionNumber
//
this.txtTransactionNumber.Location = new System.Drawing.Point(91, 57);
this.txtTransactionNumber.Name = "txtTransactionNumber";
this.txtTransactionNumber.Size = new System.Drawing.Size(158, 20);
this.txtTransactionNumber.TabIndex = 5;
//
// cmdEdit
//
this.cmdEdit.Location = new System.Drawing.Point(260, 57);
this.cmdEdit.Name = "cmdEdit";
this.cmdEdit.Size = new System.Drawing.Size(87, 30);
this.cmdEdit.TabIndex = 6;
this.cmdEdit.Text = "Edit";
this.cmdEdit.UseVisualStyleBackColor = true;
//
//
// groupBox1
//
this.groupBox1.Location = new System.Drawing.Point(438, 125);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(345, 56);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
//
// cmdBrowse
//
this.cmdBrowse.Location = new System.Drawing.Point(14, 139);
this.cmdBrowse.Name = "cmdBrowse";
this.cmdBrowse.Size = new System.Drawing.Size(220, 22);
this.cmdBrowse.TabIndex = 11;
this.cmdBrowse.Text = "Browse Unpaid Payment Requests";
this.cmdBrowse.UseVisualStyleBackColor = true;
//
// groupBox2
//
this.groupBox2.BackColor = System.Drawing.Color.WhiteSmoke;
this.groupBox2.Controls.Add(this.cmdCustomer);
this.groupBox2.Controls.Add(this.txtNotes);
this.groupBox2.Controls.Add(txtZip);
this.groupBox2.Controls.Add(txtCountry);
this.groupBox2.Controls.Add(txtState);
this.groupBox2.Controls.Add(txtCity);
this.groupBox2.Controls.Add(txtAddress);
this.groupBox2.Controls.Add(txtName);
this.groupBox2.Controls.Add(txtPayPalEmail);
this.groupBox2.Controls.Add(txtEmail);
this.groupBox2.Controls.Add(txtPhone);
this.groupBox2.Controls.Add(txtLast);
this.groupBox2.Controls.Add(txtFirst);
this.groupBox2.Location = new System.Drawing.Point(14, 168);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(749, 264);
this.groupBox2.TabIndex = 12;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Customer Information";
this.groupBox2.Enter += new System.EventHandler(this.groupBox2_Enter);
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(186, 215);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(25, 13);
this.label21.TabIndex = 24;
this.label21.Text = "Zip:";
//
// cmdCustomer
//
this.cmdCustomer.Location = new System.Drawing.Point(657, 136);
this.cmdCustomer.Name = "cmdCustomer";
this.cmdCustomer.Size = new System.Drawing.Size(86, 69);
this.cmdCustomer.TabIndex = 23;
this.cmdCustomer.Text = "Load Customer Info from Prior Order";
this.cmdCustomer.UseVisualStyleBackColor = true;
this.cmdCustomer.Click += new System.EventHandler(this.cmdCustomer_Click);
//
// txtNotes
//
this.txtNotes.AcceptsReturn = true;
this.txtNotes.Location = new System.Drawing.Point(404, 136);
this.txtNotes.Multiline = true;
this.txtNotes.Name = "txtNotes";
this.txtNotes.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtNotes.Size = new System.Drawing.Size(247, 122);
this.txtNotes.TabIndex = 19;
//
// txtZip
//
txtZip.Location = new System.Drawing.Point(211, 212);
txtZip.Name = "txtZip";
txtZip.Size = new System.Drawing.Size(99, 20);
txtZip.TabIndex = 25;
txtZip.TextChanged += new System.EventHandler(this.txtZip_TextChanged);
//
// txtCountry
//
txtCountry.Location = new System.Drawing.Point(72, 237);
txtCountry.Name = "txtCountry";
txtCountry.Size = new System.Drawing.Size(238, 20);
txtCountry.TabIndex = 22;
txtCountry.TextChanged += new System.EventHandler(this.txtCountry_TextChanged);
//
// txtState
//
txtState.Location = new System.Drawing.Point(72, 210);
txtState.Name = "txtState";
txtState.Size = new System.Drawing.Size(108, 20);
txtState.TabIndex = 21;
txtState.TextChanged += new System.EventHandler(this.txtState_TextChanged);
//
// txtCity
//
txtCity.Location = new System.Drawing.Point(72, 185);
txtCity.Name = "txtCity";
txtCity.Size = new System.Drawing.Size(238, 20);
txtCity.TabIndex = 20;
txtCity.TextChanged += new System.EventHandler(this.txtCity_TextChanged);
//
// txtAddress
//
txtAddress.AcceptsReturn = true;
txtAddress.Location = new System.Drawing.Point(72, 92);
txtAddress.Multiline = true;
txtAddress.Name = "txtAddress";
txtAddress.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
txtAddress.Size = new System.Drawing.Size(236, 87);
txtAddress.TabIndex = 18;
txtAddress.TextChanged += new System.EventHandler(this.txtAddress_TextChanged);
//
// txtName
//
txtName.Location = new System.Drawing.Point(72, 68);
txtName.Name = "txtName";
txtName.Size = new System.Drawing.Size(238, 20);
txtName.TabIndex = 17;
txtName.TextChanged += new System.EventHandler(this.txtName_TextChanged);
//
// txtPayPalEmail
//
txtPayPalEmail.Location = new System.Drawing.Point(405, 98);
txtPayPalEmail.Name = "txtPayPalEmail";
txtPayPalEmail.Size = new System.Drawing.Size(203, 20);
txtPayPalEmail.TabIndex = 16;
//
// txtEmail
//
txtEmail.Location = new System.Drawing.Point(404, 65);
txtEmail.Name = "txtEmail";
txtEmail.Size = new System.Drawing.Size(204, 20);
txtEmail.TabIndex = 15;
//
// txtPhone
//
txtPhone.Location = new System.Drawing.Point(405, 39);
txtPhone.Name = "txtPhone";
txtPhone.Size = new System.Drawing.Size(203, 20);
txtPhone.TabIndex = 14;
txtPhone.TextChanged += new System.EventHandler(this.txtPhone_TextChanged);
//
// txtLast
//
txtLast.Location = new System.Drawing.Point(189, 39);
txtLast.Name = "txtLast";
txtLast.Size = new System.Drawing.Size(121, 20);
txtLast.TabIndex = 13;
txtLast.TextChanged += new System.EventHandler(this.txtLast_TextChanged);
//
// txtFirst
//
txtFirst.Location = new System.Drawing.Point(72, 39);
txtFirst.Name = "txtFirst";
txtFirst.Size = new System.Drawing.Size(84, 20);
txtFirst.TabIndex = 12;
txtFirst.TextChanged += new System.EventHandler(this.txtFirst_TextChanged);
// grdOrderItems
//
grdOrderItems.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
grdOrderItems.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
grdOrderItems.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Qty,
this.Description,
this.UnitPrice,
this.ExtPrice,
this.SCode,
this.Options1,
this.Options2});
grdOrderItems.Location = new System.Drawing.Point(10, 19);
grdOrderItems.Name = "grdOrderItems";
grdOrderItems.Size = new System.Drawing.Size(732, 81);
grdOrderItems.TabIndex = 0;
grdOrderItems.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(grdOrderItems_CellValueChanged);
grdOrderItems.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.grdOrderItems_RowsAdded);
//
// Qty
//
this.Qty.HeaderText = "Qty";
this.Qty.Name = "Qty";
this.Qty.Width = 48;
//
// Description
//
this.Description.HeaderText = "Description";
this.Description.Name = "Description";
this.Description.Width = 85;
//
// UnitPrice
//
this.UnitPrice.HeaderText = "Unit Price";
this.UnitPrice.Name = "UnitPrice";
this.UnitPrice.Width = 78;
//
// ExtPrice
//
this.ExtPrice.HeaderText = "Ext. Price3";
this.ExtPrice.Name = "ExtPrice";
this.ExtPrice.ReadOnly = true;
this.ExtPrice.Width = 83;
//
// SCode
//
this.SCode.HeaderText = "S-Code";
this.SCode.Name = "SCode";
this.SCode.Width = 67;
//
// Options1
//
this.Options1.HeaderText = "Options1";
this.Options1.Name = "Options1";
this.Options1.Width = 74;
//
// Options2
//
this.Options2.HeaderText = "Options2";
this.Options2.Name = "Options2";
this.Options2.Width = 74;
//
// groupBox3
//
this.groupBox3.BackColor = System.Drawing.Color.WhiteSmoke;
this.groupBox3.Controls.Add(this.checkBox1);
this.groupBox3.Controls.Add(this.cmdApplyTaxRate);
this.groupBox3.Controls.Add(this.txtTaxRate);
this.groupBox3.Controls.Add(this.lblSubTotal);
this.groupBox3.Controls.Add(this.lblTotal);
this.groupBox3.Controls.Add(this.txtTax);
this.groupBox3.Controls.Add(this.txtShipping);
this.groupBox3.Controls.Add(this.txtShippingMethod);
this.groupBox3.Controls.Add(this.cmdTaxLookup);
this.groupBox3.Controls.Add(this.lstShipping);
this.groupBox3.Controls.Add(this.cmdBrowser);
this.groupBox3.Controls.Add(this.groupBox4);
this.groupBox3.Controls.Add(grdOrderItems);
this.groupBox3.Location = new System.Drawing.Point(14, 443);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(749, 242);
this.groupBox3.TabIndex = 13;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Order Information";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Location = new System.Drawing.Point(253, 224);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(257, 17);
this.checkBox1.TabIndex = 21;
this.checkBox1.Text = "Automatically Apply Tax Rate with order changes";
this.checkBox1.UseVisualStyleBackColor = true;
//
// cmdApplyTaxRate
//
this.cmdApplyTaxRate.Location = new System.Drawing.Point(313, 194);
this.cmdApplyTaxRate.Name = "cmdApplyTaxRate";
this.cmdApplyTaxRate.Size = new System.Drawing.Size(126, 24);
this.cmdApplyTaxRate.TabIndex = 20;
this.cmdApplyTaxRate.Text = "Apply Tax Rate";
this.cmdApplyTaxRate.UseVisualStyleBackColor = true;
//
// txtTaxRate
//
this.txtTaxRate.Location = new System.Drawing.Point(186, 198);
this.txtTaxRate.Name = "txtTaxRate";
this.txtTaxRate.Size = new System.Drawing.Size(101, 20);
this.txtTaxRate.TabIndex = 19;
//
// lblSubTotal
//
this.lblSubTotal.AutoSize = true;
this.lblSubTotal.Location = new System.Drawing.Point(571, 128);
this.lblSubTotal.Name = "lblSubTotal";
this.lblSubTotal.Size = new System.Drawing.Size(13, 13);
this.lblSubTotal.TabIndex = 18;
this.lblSubTotal.Text = "$";
//
// lblTotal
//
this.lblTotal.AutoSize = true;
this.lblTotal.Location = new System.Drawing.Point(571, 210);
this.lblTotal.Name = "lblTotal";
this.lblTotal.Size = new System.Drawing.Size(13, 13);
this.lblTotal.TabIndex = 17;
this.lblTotal.Text = "$";
//
// txtTax
//
this.txtTax.Location = new System.Drawing.Point(561, 177);
this.txtTax.Name = "txtTax";
this.txtTax.Size = new System.Drawing.Size(182, 20);
this.txtTax.TabIndex = 16;
//
// txtShipping
//
this.txtShipping.Location = new System.Drawing.Point(561, 149);
this.txtShipping.Name = "txtShipping";
this.txtShipping.Size = new System.Drawing.Size(182, 20);
this.txtShipping.TabIndex = 15;
//
// txtShippingMethod
//
this.txtShippingMethod.Location = new System.Drawing.Point(559, 105);
this.txtShippingMethod.Name = "txtShippingMethod";
this.txtShippingMethod.Size = new System.Drawing.Size(182, 20);
this.txtShippingMethod.TabIndex = 14;
//
// cmdTaxLookup
//
this.cmdTaxLookup.Location = new System.Drawing.Point(138, 218);
this.cmdTaxLookup.Name = "cmdTaxLookup";
this.cmdTaxLookup.Size = new System.Drawing.Size(99, 21);
this.cmdTaxLookup.TabIndex = 13;
this.cmdTaxLookup.Text = "Lookup Tax Rate";
this.cmdTaxLookup.UseVisualStyleBackColor = true;
//
// lstShipping
//
this.lstShipping.FormattingEnabled = true;
this.lstShipping.Location = new System.Drawing.Point(304, 106);
this.lstShipping.Name = "lstShipping";
this.lstShipping.Size = new System.Drawing.Size(150, 69);
this.lstShipping.TabIndex = 5;
//
// cmdBrowser
//
this.cmdBrowser.Location = new System.Drawing.Point(16, 106);
this.cmdBrowser.Name = "cmdBrowser";
this.cmdBrowser.Size = new System.Drawing.Size(164, 21);
this.cmdBrowser.TabIndex = 2;
this.cmdBrowser.Text = "Launch Browser Form";
this.cmdBrowser.UseVisualStyleBackColor = true;
this.cmdBrowser.Click += new System.EventHandler(this.cmdBrowser_Click);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.cmdSendRequest);
this.groupBox4.Location = new System.Drawing.Point(18, 133);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(162, 57);
this.groupBox4.TabIndex = 1;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "PayPal";
//
// cmdSendRequest
//
this.cmdSendRequest.Location = new System.Drawing.Point(7, 19);
this.cmdSendRequest.Name = "cmdSendRequest";
this.cmdSendRequest.Size = new System.Drawing.Size(131, 32);
this.cmdSendRequest.TabIndex = 2;
this.cmdSendRequest.Text = "Send Payment Request";
this.cmdSendRequest.UseVisualStyleBackColor = true;
this.cmdSendRequest.Click += new System.EventHandler(this.cmdSendRequest_Click_1);
//
// cmdClear
//
this.cmdClear.Location = new System.Drawing.Point(16, 696);
this.cmdClear.Name = "cmdClear";
this.cmdClear.Size = new System.Drawing.Size(67, 25);
this.cmdClear.TabIndex = 14;
this.cmdClear.Text = "Clear";
this.cmdClear.UseVisualStyleBackColor = true;
//
// cmdSave
//
this.cmdSave.Location = new System.Drawing.Point(91, 697);
this.cmdSave.Name = "cmdSave";
this.cmdSave.Size = new System.Drawing.Size(67, 25);
this.cmdSave.TabIndex = 15;
this.cmdSave.Text = "Save";
this.cmdSave.UseVisualStyleBackColor = true;
//
// cmdPrint
//
this.cmdPrint.Location = new System.Drawing.Point(164, 697);
this.cmdPrint.Name = "cmdPrint";
this.cmdPrint.Size = new System.Drawing.Size(67, 25);
this.cmdPrint.TabIndex = 16;
this.cmdPrint.Text = "Print";
this.cmdPrint.UseVisualStyleBackColor = true;
//
// cmdSavePrintEmail
//
this.cmdSavePrintEmail.Location = new System.Drawing.Point(393, 694);
this.cmdSavePrintEmail.Name = "cmdSavePrintEmail";
this.cmdSavePrintEmail.Size = new System.Drawing.Size(131, 31);
this.cmdSavePrintEmail.TabIndex = 17;
this.cmdSavePrintEmail.Text = "Save, Print, and Email";
this.cmdSavePrintEmail.UseVisualStyleBackColor = true;
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Aqua;
this.ClientSize = new System.Drawing.Size(790, 725);
this.Controls.Add(this.cmdSavePrintEmail);
this.Controls.Add(this.cmdPrint);
this.Controls.Add(this.cmdSave);
this.Controls.Add(this.cmdClear);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.cmdBrowse);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.optRequestNew);
this.Controls.Add(this.optRequestShipping);
this.Controls.Add(this.optRequestAdd);
this.Controls.Add(this.cmdEdit);
this.Controls.Add(this.txtTransactionNumber);
this.Controls.Add(this.cmdLookup);
this.Controls.Add(this.cmdExit);
this.Controls.Add(this.cmdSendEmail);
this.Name = "frmMain";
this.Text = "PayPal Payment Request Program version C1";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(grdOrderItems)).EndInit();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdSendEmail;
private System.Windows.Forms.Button cmdExit;
private System.Windows.Forms.Button cmdLookup;
private System.Windows.Forms.TextBox txtTransactionNumber;
private System.Windows.Forms.Button cmdEdit;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button cmdBrowse;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button cmdCustomer;
private System.Windows.Forms.TextBox txtNotes;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Button cmdSendRequest;
private System.Windows.Forms.Button cmdBrowser;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Button cmdApplyTaxRate;
private System.Windows.Forms.TextBox txtTaxRate;
private System.Windows.Forms.TextBox txtTax;
private System.Windows.Forms.TextBox txtShipping;
private System.Windows.Forms.TextBox txtShippingMethod;
private System.Windows.Forms.Button cmdTaxLookup;
private System.Windows.Forms.ListBox lstShipping;
private System.Windows.Forms.Button cmdClear;
private System.Windows.Forms.Button cmdSave;
private System.Windows.Forms.Button cmdPrint;
private System.Windows.Forms.Button cmdSavePrintEmail;
private System.Windows.Forms.DataGridViewTextBoxColumn Qty;
private System.Windows.Forms.DataGridViewTextBoxColumn Description;
private System.Windows.Forms.DataGridViewTextBoxColumn UnitPrice;
private System.Windows.Forms.DataGridViewTextBoxColumn ExtPrice;
private System.Windows.Forms.DataGridViewTextBoxColumn SCode;
private System.Windows.Forms.DataGridViewTextBoxColumn Options1;
private System.Windows.Forms.DataGridViewTextBoxColumn Options2;
public static System.Windows.Forms.TextBox txtEmail;
public static System.Windows.Forms.TextBox txtPhone;
public static System.Windows.Forms.TextBox txtLast;
public static System.Windows.Forms.TextBox txtCountry;
public static System.Windows.Forms.TextBox txtState;
public static System.Windows.Forms.TextBox txtAddress;
public static System.Windows.Forms.TextBox txtPayPalEmail;
public static System.Windows.Forms.DataGridView grdOrderItems;
public static System.Windows.Forms.TextBox txtZip;
public static System.Windows.Forms.TextBox txtCity;
public static System.Windows.Forms.TextBox txtName;
public static System.Windows.Forms.TextBox txtFirst;
}
}
If you look into the .designer.cs file carefully you will notice this little comment
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
Basically that part of the code are auto generated by the designer and should never be modified manually.
And yes this is considered bad practice. Firstly the control should be self contained inside the form instead of being a static one. Static just means there will only be one instance across all the forms of the same class.
Direct modification of UI from one form to another is considered anti-pattern as well. You should be making a Data model and have the UI reads the updated data when they are changed. I know this might be a bit challenging for beginners as well for winform.
So if you want to take the shortcut you can expose a public property on the other form and by modifying the property your other form will update the appropriate control.
Edit:
In the other form's code behind (.cs file)
you can do like
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string SelectedUser { get; private set; }
}
and then in your main form you would listen to the close event
Form1 other = new Form1();
other.FormClosed += Other_FormClosed;
other.Show();
...
private void Other_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 other = (Form1)sender;
string selectedUser = other.SelectedUser;
//do something
}

Store data from 4 textboxes into a simple array

I need help with storing data from 4 textboxes into an array and writing the data to binary file.
This is what I need to specifically:
Store the data from 4 textboxes into a simple array then add a save button which will:
Store the information in the 4 text boxes to the array
Add the information in the 4 text boxes as four separate items to a binary
file books.dat which is sorted by Title
This is my code so far:
Concatenate Button:
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = new string[8];
int index1 = 0;
string text1 = this.txtAuthor.Text;
strArray[index1] = text1;
int index2 = 1;
string str1 = ", ";
strArray[index2] = str1;
int index3 = 2;
string text2 = this.txtDate.Text;
strArray[index3] = text2;
int index4 = 3;
string str2 = ". ";
strArray[index4] = str2;
int index5 = 4;
string text3 = this.txtTitle.Text;
strArray[index5] = text3;
int index6 = 5;
string str3 = ". ";
strArray[index6] = str3;
int index7 = 6;
string text4 = this.txtPublisher.Text;
strArray[index7] = text4;
int index8 = 7;
string str4 = ".";
strArray[index8] = str4;
this.txtOutput.Text = string.Concat(strArray);
}
Protected Override:
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
Initialize Component:
private void InitializeComponent()
{
this.txtAuthor = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.txtDate = new System.Windows.Forms.TextBox();
this.txtTitle = new System.Windows.Forms.TextBox();
this.txtPublisher = new System.Windows.Forms.TextBox();
this.txtOutput = new System.Windows.Forms.TextBox();
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.btnSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtAuthor
//
this.txtAuthor.Location = new System.Drawing.Point(14, 27);
this.txtAuthor.Name = "txtAuthor";
this.txtAuthor.Size = new System.Drawing.Size(100, 20);
this.txtAuthor.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(14, 53);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(418, 23);
this.button1.TabIndex = 1;
this.button1.Text = "Concatenate";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtDate
//
this.txtDate.Location = new System.Drawing.Point(120, 27);
this.txtDate.Name = "txtDate";
this.txtDate.Size = new System.Drawing.Size(100, 20);
this.txtDate.TabIndex = 2;
//
// txtTitle
//
this.txtTitle.Location = new System.Drawing.Point(226, 27);
this.txtTitle.Name = "txtTitle";
this.txtTitle.Size = new System.Drawing.Size(100, 20);
this.txtTitle.TabIndex = 4;
//
// txtPublisher
//
this.txtPublisher.Location = new System.Drawing.Point(332, 27);
this.txtPublisher.Name = "txtPublisher";
this.txtPublisher.Size = new System.Drawing.Size(100, 20);
this.txtPublisher.TabIndex = 6;
//
// txtOutput
//
this.txtOutput.Location = new System.Drawing.Point(14, 82);
this.txtOutput.Name = "txtOutput";
this.txtOutput.ReadOnly = true;
this.txtOutput.Size = new System.Drawing.Size(418, 20);
this.txtOutput.TabIndex = 8;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(11, 11);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(38, 13);
this.label1.TabIndex = 9;
this.label1.Text = "Author";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(117, 11);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(30, 13);
this.label2.TabIndex = 10;
this.label2.Text = "Date";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(223, 11);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(27, 13);
this.label3.TabIndex = 11;
this.label3.Text = "Title";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(329, 11);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(50, 13);
this.label4.TabIndex = 12;
this.label4.Text = "Publisher";
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(14, 108);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(418, 23);
this.btnSave.TabIndex = 13;
this.btnSave.Text = "Save";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(446, 142);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.txtPublisher);
this.Controls.Add(this.txtTitle);
this.Controls.Add(this.txtDate);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtAuthor);
this.Name = "Form1";
this.Text = "Book Details";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
Book Class:
private class Book
{
private string Author
{
get
{
return this.Author;
}
set
{
this.Author = value;
}
}
private string Date
{
get
{
return this.Date;
}
set
{
this.Date = value;
}
}
private string Title
{
get
{
return this.Title;
}
set
{
this.Title = value;
}
}
private string Publisher
{
get
{
return this.Publisher;
}
set
{
this.Publisher = value;
}
}
}
Empty Save Button:
private void btnSave_Click(object sender, EventArgs e)
{
}
I would suggest that you are going about this the wrong way. My understanding of the problem is that you want to create your "Book" class from the 4 inputs in your GUI, which is Serializable. In this case I would modify your book class to contain a constructor which takes 4 arguments (title, author, publisher and date):
internal class Book
{
public Book(string title, string author, string publisher, string date)
{
Title = title;
Author = author;
Publisher = publisher;
Date = date;
}
public string Title { get; private set; }
public string Author { get; private set; }
public string Publisher { get; private set; }
public string Date { get; private set; }
public override string ToString()
{
return string.Format("{0}, {1}. {2}. {3}.", Author, Date, Title, Publisher);
}
}
Then your button1_Click method can look like:
private void button1_Click(object sender, EventArgs e)
{
var title = this.txtTitle.Text;
// var author, date, publisher are similar
this.currentBook = new Book(title, author, publisher, date);
}
Where currentBook is a member variable of type Book.
Finally your save button method would now look like:
private void btnSave_Click(object sender, EventArgs e)
{
var currentBookText = this.currentBook.ToString();
// write currentBookText to file.
}
You can look at: https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx for information about writing to a file.
You could then easily create a public static Book Book.FromString(string input) method to de-serialize your book files.
C# can also handle the serialization and de-serialization for you. For more information look here: https://msdn.microsoft.com/en-us/library/et91as27.aspx

Categories