How to get event for ComboBox inside of Gridview using C# Windows Application... Anyone Tell me the solution of this problem.....
Thanks in Advance...
check this http://www.eggheadcafe.com/community/aspnet/2/10098379/gridview.aspx
I think you are looking at the wrong place. For value change event, you should use your class's property changed event that is bound to that specific column in the GridView. Because, when you change value in the ComboBoxColumn, it will in turn update the value in the object that is bound to that row.
Example:
Designer generated code
`partial class Form1
{
///
/// Required designer variable.
///
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.dataGridView1 = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location = new System.Drawing.Point(0, 0);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowTemplate.Height = 24;
this.dataGridView1.Size = new System.Drawing.Size(282, 255);
this.dataGridView1.TabIndex = 0;
//
// Column1
//
this.Column1.DataPropertyName = "Value1";
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
//
// Column2
//
this.Column2.DataPropertyName = "Value2";
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(282, 255);
this.Controls.Add(this.dataGridView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.DataGridViewComboBoxColumn Column1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
}`
Code Behind
`public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Column1 is
Column1.DataPropertyName = "Value1";
Column1.Items.AddRange(Enumerable.Range(1, 10).Select(i => i.ToString()).ToArray());
Column2.DataPropertyName = "Value2";
dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
dataGridView1.DataSource = (from obj in Enumerable.Range(1, 20)
select new Model() { Value1 = obj, Value2 = ("Value2 #" + obj.ToString()) }).ToList();
}
void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.Exception.ToString());
}
}
class Model
{
protected Int32 _value1;
public Int32 Value1
{
get
{
return _value1;
}
set
{
// Here is your property change event
MessageBox.Show(value.ToString());
_value1 = value;
}
}
public String Value2 { get; set; }
}`
Related
I'm making a Web Browser, but I don't know how to add these buttons on top of its ContextMenuStrip:
A Sepator make columns for all items, but no for only one line.
Do you have any idea how to make that?
Here's a custom Component, inheriting ToolStripControlHost (as the .Net's ToolStripTextBox, ToolStripComboBox etc.) that hosts an UserControl instead of a standard Control.
▶ Building an UserControl, you can add whatever other Controls to its surface and manage their actions as usual, except the UserControl's Events are exposed through the ToolStripControlHost derived object, so implementers don't need to know anything about the underlying hosted Control.
The hosted Control's events that you want to expose are subscribe to overriding OnSubscribeControlEvents() (and of course unsubscribed to overriding OnUnsubscribeControlEvents), then raising a related or composed event that returns values as needed.
▶ This is shown in the ToolStripControlHost class, see the public event EventHandler<UserActionArgs> ButtonAction event, an event that returns a custom EventArgs argument that includes elements that are needed to determine the action performed by the Button clicked.
When needed, the hosted Control is exposed through the ToolStripControlHost.Control property.
You can initialize an existing ContextMenuStrip (contextMenuStrip1, here) in the constructor of the Form that uses it:
public partial class Form1 : Form
{
private ToolStripUserControl toolStripUC = new ToolStripUserControl();
public Form1()
{
InitializeComponent();
// Assigns an existing ContextMenuStrip, to the Form or any other Control
this.ContextMenuStrip = contextMenuStrip1;
// Inserts the ToolStripUserControl and a Separator
contextMenuStrip1.Items.Insert(0, new ToolStripSeparator());
contextMenuStrip1.Items.Insert(0, toolStripUC);
// Subscribes to the ButtonAction event
toolStripUC.ButtonAction += (s, e)
=> { this.Text = $"Your Action is {e.UserAction}, triggered by {e.TriggerControl.Name}"; };
contextMenuStrip1.Closed += (s, e) => this.Text = "Right-Click on me";
}
}
ToolStripControlHost derived class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
[ToolboxItem(false)]
public class ToolStripUserControl : ToolStripControlHost
{
// Pass the UserControl, MenuStripNavigationBar, to the base class.
public ToolStripUserControl() : base(new MenuStripNavigationBar()) { }
public MenuStripNavigationBar NavigatorBar => Control as MenuStripNavigationBar;
// Exposes the ButtonActions Dictionary, to redefine the Buttons' actions
public Dictionary<Control, ButtonAction> ButtonActions {
get => NavigatorBar.ButtonActions;
set => NavigatorBar.ButtonActions = value;
}
// Subscribe to the events you want to expose...
protected override void OnSubscribeControlEvents(Control ctl)
{
base.OnSubscribeControlEvents(ctl);
var navigatorBar = (MenuStripNavigationBar)ctl;
navigatorBar.UserAction += OnButtonAction;
}
// ...and then unsubscribe. This is called when the Form is destroyed
protected override void OnUnsubscribeControlEvents(Control ctl)
{
base.OnUnsubscribeControlEvents(ctl);
var navigatorBar = (MenuStripNavigationBar)ctl;
navigatorBar.UserAction -= OnButtonAction;
}
// Exposes a public custom event
public event EventHandler<UserActionArgs> ButtonAction;
// Raises the event when an UserAction is triggered
private void OnButtonAction(object sender, EventArgs e)
{
var ctl = sender as Control;
var userAction = new UserActionArgs(ButtonActions[ctl], ctl);
ButtonAction?.Invoke(this, userAction);
}
}
Custom EventArgs object:
public class UserActionArgs : EventArgs
{
public UserActionArgs(ButtonAction action, Control control)
{
this.UserAction = action;
this.TriggerControl = control;
}
public ButtonAction UserAction { get; }
public Control TriggerControl { get; }
}
Actions enumerator:
public enum ButtonAction
{
MoveBack,
MoveForward,
PlayMusic,
PlayAnimation
}
This is how it works:
This is the full UserControl, to ease testing:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public partial class MenuStripNavigationBar : UserControl
{
public event EventHandler UserAction;
public MenuStripNavigationBar()
{
InitializeComponent();
this.ButtonActions = new Dictionary<Control, ButtonAction>();
this.buttonArrowLeft.Text = "⏪";
ButtonActions.Add(this.buttonArrowLeft, ButtonAction.MoveBack);
this.buttonArrowLeft.Click += ButtonsActionEvent;
this.buttonArrowRight.Text = "⏩";
ButtonActions.Add(this.buttonArrowRight, ButtonAction.MoveBack);
this.buttonArrowRight.Click += ButtonsActionEvent;
this.buttonMusicKey.Text = "♬";
ButtonActions.Add(this.buttonMusicKey, ButtonAction.PlayMusic);
this.buttonMusicKey.Click += ButtonsActionEvent;
this.buttonAction.Text = "⛄";
ButtonActions.Add(this.buttonAction, ButtonAction.PlayAnimation);
this.buttonAction.Click += ButtonsActionEvent;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Dictionary<Control, ButtonAction> ButtonActions { get; set; }
private void ButtonsActionEvent(object sender, EventArgs e)
=> UserAction?.Invoke(sender, e);
[ToolboxItem(false)]
internal class ButtonPanel : Panel
{
private Color borderActiveColor = Color.LightSteelBlue;
private Color borderInactiveColor = Color.Gray;
private Color borderColor = Color.Transparent;
public ButtonPanel()
{
this.SetStyle(ControlStyles.Selectable | ControlStyles.SupportsTransparentBackColor |
ControlStyles.UserMouse | ControlStyles.StandardClick, true);
this.UpdateStyles();
this.BackColor = Color.Transparent;
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
this.OnEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
this.OnLeave(e);
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
bool hovered = this.ClientRectangle.Contains(this.PointToClient(MousePosition));
borderColor = hovered ? Enabled ? borderActiveColor : borderInactiveColor : Color.Transparent;
this.Invalidate();
}
protected override void OnLeave(EventArgs e)
{
if (this.ClientRectangle.Contains(this.PointToClient(MousePosition))) return;
borderColor = Color.Transparent;
base.OnLeave(e);
this.Invalidate();
}
TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding | TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.SingleLine;
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var textRect = Rectangle.Inflate(ClientRectangle, 0, -1);
TextRenderer.DrawText(e.Graphics, Text, Font, textRect, ForeColor, Color.Empty, flags);
ControlPaint.DrawBorder(e.Graphics, ClientRectangle, borderColor, ButtonBorderStyle.Solid);
}
}
}
Designer file:
partial class MenuStripNavigationBar
{
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.buttonAction = new MenuStripNavigationBar.ButtonPanel();
this.buttonArrowLeft = new MenuStripNavigationBar.ButtonPanel();
this.buttonArrowRight = new MenuStripNavigationBar.ButtonPanel();
this.buttonMusicKey = new MenuStripNavigationBar.ButtonPanel();
this.SuspendLayout();
//
// buttonAction
//
this.buttonAction.BackColor = System.Drawing.Color.Transparent;
this.buttonAction.Font = new System.Drawing.Font("Segoe UI Symbol", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonAction.Location = new System.Drawing.Point(166, 2);
this.buttonAction.Name = "buttonAction";
this.buttonAction.Size = new System.Drawing.Size(42, 26);
this.buttonAction.TabIndex = 0;
//
// buttonArrowLeft
//
this.buttonArrowLeft.BackColor = System.Drawing.Color.Transparent;
this.buttonArrowLeft.Font = new System.Drawing.Font("Segoe UI Symbol", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonArrowLeft.Location = new System.Drawing.Point(3, 2);
this.buttonArrowLeft.Name = "buttonArrowLeft";
this.buttonArrowLeft.Size = new System.Drawing.Size(42, 26);
this.buttonArrowLeft.TabIndex = 0;
//
// buttonArrowRight
//
this.buttonArrowRight.BackColor = System.Drawing.Color.Transparent;
this.buttonArrowRight.Font = new System.Drawing.Font("Segoe UI Symbol", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonArrowRight.Location = new System.Drawing.Point(58, 2);
this.buttonArrowRight.Name = "buttonArrowRight";
this.buttonArrowRight.Size = new System.Drawing.Size(42, 26);
this.buttonArrowRight.TabIndex = 0;
//
// buttonMusicKey
//
this.buttonMusicKey.BackColor = System.Drawing.Color.Transparent;
this.buttonMusicKey.Font = new System.Drawing.Font("Segoe UI Symbol", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonMusicKey.Location = new System.Drawing.Point(112, 2);
this.buttonMusicKey.Name = "buttonMusicKey";
this.buttonMusicKey.Size = new System.Drawing.Size(42, 26);
this.buttonMusicKey.TabIndex = 0;
//
// MenuStripNavigationBar
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.buttonMusicKey);
this.Controls.Add(this.buttonArrowRight);
this.Controls.Add(this.buttonArrowLeft);
this.Controls.Add(this.buttonAction);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.MaximumSize = new System.Drawing.Size(212, 30);
this.MinimumSize = new System.Drawing.Size(212, 30);
this.Name = "MenuStripNavigationBar";
this.Size = new System.Drawing.Size(212, 30);
this.ResumeLayout(false);
}
private ButtonPanel buttonAction;
private ButtonPanel buttonArrowLeft;
private ButtonPanel buttonArrowRight;
private ButtonPanel buttonMusicKey;
}
This is my form1 which I designed. When I type emp id in form1's textbox and click on the search button it shows form2.
In this second form I need to carry all the details corresponding to emp id and should display details into corresponding textboxes.
I have created emp table in SQL Server...I would like to pull the employee details from the database based on emp id. This is my code:
form1:
private void btnsearch_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(tbempid.Text);
f2.Show();
SqlConnection con = new SqlConnection("Data Source=RAJIM-PC;Initial Catalog=Practicing;User ID=sa;Password=RajiSha");
try
{
con.Open();
SqlCommand com = new SqlCommand("SELECT eid,emp_name,mobile_no FROM emp WHERE ID='" + tbempid.Text.Trim() + "'", con);
com.CommandType = CommandType.Text;
DataTable dtb = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dtb);
if (dtb.Rows.Count > 0)
{
Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
}
FormCollection fc = System.Windows.Forms.Application.OpenForms;
foreach (Form f in fc)
{
if (f.Name == "Form2")
{
f.Update();
}
}
}
catch (SqlException sql)
{
System.Windows.Forms.MessageBox.Show(sql.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
con.Dispose();
}
}
}
form2:
public partial class Form2 : Form
{
public static string txtempid;
public static string txtempname;
public static string txtmbno;
public Form2(string strtxtbox)
{
InitializeComponent();
tbempid.Text = strtxtbox;
}
}
Looks like your doing all the work for filling out Form2 in Form1, I would suggest moving the code into Form2 and calling it from the Form2's constructor. Not only will this make more sense, but means you will only hit your database once to get the results.
Alternatively, you could pass Form2 your data table from Form1 and use the values in Form2's constructor. Again, saving a second query going to the database.
You can take constructor of form 2 as shown below :-
public Form2(string txtempid, string txtempname, string txtmbno)
{
InitializeComponent();
txtempid.Text = txtempid;
txtempname.Text = txtempname;
txtmbno.Text = txtmbno;
}
and in form 1 :-
var form2 = new Form2(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());
You should change Form2 to f2 here:
Form2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
Form2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
Form2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
So it becomes:
f2.txtempid.Text= dtb.Rows[0]["eid"].ToString();
f2.txtempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.txtmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
Update 1
You are trying to assign those fields to the string variables. However, what you should do is to assign them to relevant textbox controls like this:
Assume you have 3 textboxes named tbempid, tbempname, tbmbno on Form2
f2.tbempid.Text= dtb.Rows[0]["eid"].ToString();
f2.tbempname.Text = dtb.Rows[0]["emp_name"].ToString();
f2.tbmbno.Text= dtb.Rows[0]["mobile_no"].ToString();
Update 2
Due to the protection level, you need to add a function in Form2:
public void SetTextBoxes(string strempid, string strempname, string strmbno)
{
tbempid.Text = strempid;
tbempname.Text = strempname;
tbmbno.Text = strmbno;
}
And change the 3 lines to:
f2.SetTextBoxes(dtb.Rows[0]["eid"].ToString(), dtb.Rows[0]["emp_name"].ToString(), dtb.Rows[0]["mobile_no"].ToString());
The following is a very quick example that I've thrown together of what I suggested above. It does not follow best practice for purposes of simplicity. The areas to concentrate on below is the EmployeeModel class, Form1 and Form2 source.
The idea here is utilize the EmployeeModel class as a container that both forms have access to.
Form 1 acquires the employee information. (Keep in mind, the model class can contain any information you like. It does not have to be reserved for just properties. If you prefer, you can keep a reference to a dataset here.)
Form 2 has a reference to this EmployeeModel class. When the button click event is fired on form1, a new EmployeeModel class object is created and initialized with the relevant information that would be displayed in form2. It is then passed as an object reference using Form2's overloaded constructor.
On the Onload event of Form2, the label.Text properties are initialized with what is contained in the EmployeeModel that was passed as a reference.
This is a very basic implementation and in most real world applications where expandability and maintainability are also factors to consider, a MVP or MVVM WinForms architectural framework is typically used.
Form 1 designer:
namespace FormToFormExample
{
partial class Form1
{
/// <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.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 12);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(260, 20);
this.textBox1.TabIndex = 0;
//
// button1
//
this.button1.Location = new System.Drawing.Point(197, 64);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 100);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
}
}
Form 2 designer:
namespace FormToFormExample
{
partial class Form2
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 34);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 1;
this.label2.Text = "label2";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form2";
this.Text = "Form2";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
}
}
Model class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FormToFormExample
{
public class EmployeeModel
{
#region Properties
private Guid _employeeID;
public Guid EmployeeID
{
get { return this._employeeID; }
set { this._employeeID = value; }
}
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
#endregion
#region Constructors
public EmployeeModel()
{
this._employeeID = Guid.NewGuid();
}
public EmployeeModel(string name)
: this()
{
this._name = name;
}
#endregion
}
}
Form 1 source:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
public partial class Form1 : Form
{
#region Constructors
public Form1()
{
InitializeComponent();
Initialize();
BindComponents();
}
#endregion
#region Methods
private void BindComponents()
{
this.button1.Click += button1_Click;
}
private void Initialize()
{
this.textBox1.Text = string.Empty;
}
#endregion
#region Events
void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(new EmployeeModel(textBox1.Text));
form2.ShowDialog();
Initialize();
}
#endregion
}
}
Form 2 source:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
public partial class Form2 : Form
{
EmployeeModel _model;
#region Constructors
public Form2()
{
InitializeComponent();
BindComponents();
}
public Form2(EmployeeModel model)
: this()
{
this._model = model;
}
#endregion
#region Methods
private void BindComponents()
{
this.Load += Form2_Load;
}
private void Initialize()
{
this.label1.Text = this._model.EmployeeID.ToString();
this.label2.Text = this._model.Name;
}
#endregion
#region Events
void Form2_Load(object sender, EventArgs e)
{
Initialize();
}
#endregion
}
}
Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FormToFormExample
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Ok so I am testing with adding a picturebox to my winform app. I am finally asking here, because when ever I look up how to do this I don't see anything different than what I am doing. Here is the code:
namespace AddPanel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pictureBox1 = new PictureBox();
pictureBox1.ImageLocation = #"C:\Users\xoswaldr\Desktop\OrangeLogo.jpg";
pictureBox1.Location = new System.Drawing.Point(20, 40);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new System.Drawing.Size(100, 50);
pictureBox1.BackColor = Color.Black;
this.Controls.Add(pictureBox1);
}
}
}
That is the entire code, because I am just trying to test adding a picturebox for something else I'm working on. What I am trying to do with this is when I run the program it puts the picturebox in the form, but that doesn't happen. The form is just blank.
-----EDIT------------
Here is the Form1.Designer.cs code
namespace AddPanel
{
partial class Form1
{
/// <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.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(690, 381);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
}
and here is the Program.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace AddPanel
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Is there something in the designer that is blocking it or something that I haven't added?
Since your code looks correct, is it possible there is another control covering the picture box?
Try bringing it to the Front:
private void Form1_Load(object sender, EventArgs e)
{
var pictureBox1 = new PictureBox
{
BackColor = Color.Black,
ImageLocation = #"C:\Users\xoswaldr\Desktop\OrangeLogo.jpg",
Location = new Point(20, 40),
Name = "pictureBox1",
Size = new Size(100, 50)
};
this.Controls.Add(pictureBox1);
pictureBox1.BringToFront();
}
The picture may not be completely displayed, just set the SizeMode to have a try:
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom
I need to write something to autoscroll a text in a single line TextBox continuously. Do I need to scroll to caret then set it to first char and start over?
So i found a marquee control and modify it a little and used it instead of textbox
public class Marquee : System.Windows.Forms.UserControl
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Timer timer1;
private int currentPos = 0;
private bool mBorder;
private string mText;
public string MarqueeText
{
get { return mText; }
set { mText = value; }
}
public bool Border
{
get { return mBorder; }
set { mBorder = value; }
}
public int Interval
{
get { return timer1.Interval * 10; }
set { timer1.Interval = value / 10; }
}
public Marquee()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitForm call
this.Size = new Size(this.Width, this.Font.Height);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Component 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.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Marquee
//
this.Name = "Marquee";
this.Size = new System.Drawing.Size(150, 136);
this.Resize += new System.EventHandler(this.Marquee_Resize);
}
#endregion
private void Marquee_Resize(object sender, System.EventArgs e)
{
this.Height = this.Font.Height;
}
private void timer1_Tick(object sender, System.EventArgs e)
{
this.Invalidate();
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
if (mBorder)
{
e.Graphics.DrawRectangle(new Pen(this.ForeColor), 0, 0, this.Width - 1, this.Height - 1);
}
float dif = e.Graphics.MeasureString(mText, this.Font).Width- this.Width;
if (this.Width < e.Graphics.MeasureString(mText, this.Font).Width)
{
e.Graphics.DrawString(mText, this.Font, new SolidBrush(this.ForeColor),
currentPos, 0);
e.Graphics.DrawString(mText, this.Font, new SolidBrush(this.ForeColor),
this.Width + currentPos + dif, 0);
currentPos--;
if ((currentPos < 0) && (Math.Abs(currentPos) >= e.Graphics.MeasureString(mText, this.Font).Width))
currentPos = this.Width + currentPos;
}
else
{
e.Graphics.DrawString(mText, this.Font, new SolidBrush(this.ForeColor),-dif/2, 0);
}
}
}
So if the text width is longer than the width of the control the text will be static else the text will auto-scroll
Similar to this question:
get contextmenustrip from toolstripmenuitem
Except that now I need to find the object whose context menu was opened when the ToolStripMenuItem was clicked.
SourceControl, Parent, Owner, and GetParentControl() all return null.
Initially I had a TreeView, and it's ContextMenuStrip property was set.
Here's my preliminary code:
ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
ToolStripMenuItem tsmip = (ToolStripMenuItem)tsmi.OwnerItem;
ContextMenuStrip cms = (ContextMenuStrip)tsmip.GetCurrentParent();
TreeView tv = (TreeView)cms.SourceControl;
// returns null, but not in the cms_openHandler
tv.Nodes.Add(new TreeNode("event fired."));
Am I getting the ContextMenuStrip improperly? Why is it that the SourceControl property of the cms works in the OpenHandler, but not from the ToolStripMenuItem eventhandler?
Form1.Designer.cs:
namespace TestWFA
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
this.treeView1 = new System.Windows.Forms.TreeView();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.expandToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.childrenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.allDescendantsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.collapseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.childrenToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.parentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.childrenToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.allDescendantsToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.ContextMenuStrip = this.contextMenuStrip1;
this.treeView1.Location = new System.Drawing.Point(64, 75);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(262, 247);
this.treeView1.TabIndex = 0;
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.expandToolStripMenuItem,
this.collapseToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening);
//
// expandToolStripMenuItem
//
this.expandToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.childrenToolStripMenuItem,
this.allDescendantsToolStripMenuItem});
this.expandToolStripMenuItem.Name = "expandToolStripMenuItem";
this.expandToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.expandToolStripMenuItem.Text = "Expand";
//
// childrenToolStripMenuItem
//
this.childrenToolStripMenuItem.Name = "childrenToolStripMenuItem";
this.childrenToolStripMenuItem.Size = new System.Drawing.Size(161, 22);
this.childrenToolStripMenuItem.Text = "Children";
this.childrenToolStripMenuItem.Click += new System.EventHandler(this.childrenToolStripMenuItem_Click);
//
// allDescendantsToolStripMenuItem
//
this.allDescendantsToolStripMenuItem.Name = "allDescendantsToolStripMenuItem";
this.allDescendantsToolStripMenuItem.Size = new System.Drawing.Size(161, 22);
this.allDescendantsToolStripMenuItem.Text = "All Descendants";
this.allDescendantsToolStripMenuItem.Click += new System.EventHandler(this.allDescendantsToolStripMenuItem_Click);
//
// collapseToolStripMenuItem
//
this.collapseToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.childrenToolStripMenuItem1,
this.parentToolStripMenuItem,
this.childrenToolStripMenuItem2,
this.allDescendantsToolStripMenuItem1});
this.collapseToolStripMenuItem.Name = "collapseToolStripMenuItem";
this.collapseToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.collapseToolStripMenuItem.Text = "Collapse";
//
// childrenToolStripMenuItem1
//
this.childrenToolStripMenuItem1.Name = "childrenToolStripMenuItem1";
this.childrenToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.childrenToolStripMenuItem1.Text = "All Ancestors";
this.childrenToolStripMenuItem1.Click += new System.EventHandler(this.childrenToolStripMenuItem1_Click);
//
// parentToolStripMenuItem
//
this.parentToolStripMenuItem.Name = "parentToolStripMenuItem";
this.parentToolStripMenuItem.Size = new System.Drawing.Size(161, 22);
this.parentToolStripMenuItem.Text = "Parent";
this.parentToolStripMenuItem.Click += new System.EventHandler(this.parentToolStripMenuItem_Click);
//
// childrenToolStripMenuItem2
//
this.childrenToolStripMenuItem2.Name = "childrenToolStripMenuItem2";
this.childrenToolStripMenuItem2.Size = new System.Drawing.Size(161, 22);
this.childrenToolStripMenuItem2.Text = "Children";
this.childrenToolStripMenuItem2.Click += new System.EventHandler(this.childrenToolStripMenuItem2_Click);
//
// allDescendantsToolStripMenuItem1
//
this.allDescendantsToolStripMenuItem1.Name = "allDescendantsToolStripMenuItem1";
this.allDescendantsToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.allDescendantsToolStripMenuItem1.Text = "All Descendants";
this.allDescendantsToolStripMenuItem1.Click += new System.EventHandler(this.allDescendantsToolStripMenuItem1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(406, 365);
this.Controls.Add(this.treeView1);
this.Name = "Form1";
this.Text = "Form1";
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem expandToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem childrenToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem allDescendantsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem collapseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem childrenToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem parentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem childrenToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem allDescendantsToolStripMenuItem1;
}
}
Form1.cs:
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;
namespace TestWFA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
treeView1.Nodes.Add(new TreeNode("root"));
}
private void childrenToolStripMenuItem1_Click(object sender, EventArgs e)
{
TreeView tv = GetSourceControl(sender) as TreeView;
if (tv != null)
{
tv.Nodes.Add("Tree event catched!");
}
/*ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
ToolStripMenuItem tsmip = (ToolStripMenuItem)tsmi.OwnerItem;
ContextMenuStrip cms = (ContextMenuStrip)tsmip.GetCurrentParent();
ToolStrip ts = tsmip.GetCurrentParent();
IContainer c = cms.Container;
TreeView tv = (TreeView)c;
tv.Nodes.Add(new TreeNode("event fired."));*/
}
private object GetSourceControl(object Sender)
{
if (Sender as ContextMenuStrip != null)
{
return ContextMenuStrip.SourceControl;
}
var item = Sender as ToolStripItem;
// move to root item
while (item.OwnerItem != null)
{
item = item.OwnerItem;
}
// we have root item now, so lets take ContextMenuStrip object
var menuObject = item.Owner as ContextMenuStrip;
if (menuObject != null)
{
return menuObject.SourceControl;
}
return null;
}
private void parentToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void childrenToolStripMenuItem2_Click(object sender, EventArgs e)
{
}
private void allDescendantsToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void childrenToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void allDescendantsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
try
{
ContextMenuStrip cms = (ContextMenuStrip)sender;
}
catch
{
}
try
{
TreeView tv = (TreeView)sender;
}
catch
{
}
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestWFA
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Unfortunately I don't know of any way to upload the files. I tried uploading them as imgs, that didn't work.
Suppose you have ContextMenuStrip setted to TreeView. You can easily get control for which menu was triggered from Opened handler for your ContextMenuStrip:
private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
TreeView tv = (sender as ContextMenuStrip).SourceControl as TreeView;
tv.Nodes.Add("Tree event catched!");
}
This code would also work if ContextMenuStrip was set to treeView's item.
PS: In real app you shouldn't use construction like (sender as ContextMenuStrip).SourceControl as TreeView; because of possibility of null pointer. You should check for null after each cast instead.
[EDIT]
OK, now I understand your aim.
When you handle menu item sender object points to item triggered event. And to find out the control for which context menu was popped up you should do three things:
Find root item. Its likely, that clicked item is subitem for another item or deeper.
From root item you should find out ContextMenuStrip object
It's easy to find out interesting control from ContextMenuStrip's SourceControl property
I wrote simple method to do all that job:
/// <summary>
/// Gets controls for context menu
/// </summary>
/// <param name="Sender">Sender object from menu event handler</param>
/// <returns></returns>
private object GetSourceControl(Object Sender)
{
// ContextMenuStrip sended?
if (Sender as ContextMenuStrip != null)
{
ContextMenuStrip cms = Sender as ContextMenuStrip;
return cms.SourceControl;
}
var item = Sender as ToolStripItem;
// move to root item
while (item.OwnerItem != null)
{
item = item.OwnerItem;
}
// we have root item now, so lets take ContextMenuStrip object
var menuObject = item.Owner as ContextMenuStrip;
if (menuObject != null)
{
return menuObject.SourceControl;
}
return null;
}
You can simply use it. For example we have menu item click event handler:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
TreeView tv = GetSourceControl(sender) as TreeView;
if (tv != null)
{
tv.Nodes.Add("Tree event catched!");
}
}
[EDIT2]
As turned out this problem was discused early ( SourceControl of ContextMenuStrip is Nothing in ToolStripMenuItem Click? ). SourceControl property is not null when you are click on root item, but in case you click subitem it equals null. So the solution is to store SourceControl's value somwhere to use later. I suggest to do this in Tag property. So all methods would be looks like:
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
contextMenuStrip1.Tag = (sender as ContextMenuStrip).SourceControl;
}
....
private object GetSourceControl(object Sender)
{
if (Sender as ContextMenuStrip != null)
{
return ContextMenuStrip.SourceControl;
}
var item = Sender as ToolStripItem;
// move to root item
while (item.OwnerItem != null)
{
item = item.OwnerItem;
}
// we have root item now, so lets take ContextMenuStrip object
var menuObject = item.Owner as ContextMenuStrip;
if (menuObject != null)
{
return menuObject.Tag;
}
return null;
}
In the linked question there is workaround with private field, but Tag property is habitual for me