C#- Get Control text that created at runtime - c#

How I can get text of a control that was created at runtime?
private void button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Top = 50;
btn.Left = 50;
btn.Name = "mybtn";
btn.Text = "My button";
this.Controls.Add(btn);
}
private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine(mybtn.text); // error
}

var b = this.Controls.OfType<Button>().FirstOrDefault(b => b.Name == "mybtn");
if (b == null) { return; }
Console.WriteLine(b.Text);

private void button2_Click(object sender, EventArgs e)
{
// find mybtn
Button mybtn = this.Controls.FirstOrDefault(i => i.Name == "mybtn") as Button;
if (mybtn != null)
{
Console.WriteLine(mybtn.Text);
}
}

Either declare newly created control as a class member(property or field):
Button btn ;
private void button1_Click(object sender, EventArgs e)
{
btn = new Button();
btn.Top = 50;
btn.Left = 50;
btn.Name = "mybtn";
btn.Text = "My button";
this.Controls.Add(btn);
}
OR
search it through the form controls:
private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine(this.Controls.Cast<Control>().Single(p=>p.Name == "mybtn").Text);
}

private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine(this.Controls.Find("myBtn", false).FirstOrDefault().Text);
}

Related

How to get an attribute from an unspecified object?

My program dynamically creates a number of buttons at runtime. All of them get attached to an EventHandler, which links to the same method. How to know which button was pressed when the method executes? I tried using sender.Name, because object sender is a Button at runtime, but it doesn't compile.
List<Button> buttons = new List<Button>();
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i < 3; i++)
{
buttons.Add(new Button() { Name = "btn" + i });
buttons.Last().Click += new EventHandler(btn_Click);
}
}
public void btn_Click(object sender, EventArgs e)
{
MessageBox.Show(sender.Name + " is clicked");
}
You are on the right track.
The problem you have is that in btn_Click the sender is a generic object, so the compiler doesn't know what type it is, so you need to tell it by casting.
public void btn_Click(object sender, EventArgs e)
{
Button senderButton = (Button)sender;
MessageBox.Show(senderButton.Name + " is clicked");
}

Scroll Mdi Child Form on Object Move like Pan window in C#

I am creating a Pan window application in this application when I have a window with transparent object when I moved this object at the same time mdi scroll will also scroll as per this below image. This image is an example of my current application. https://i.stack.imgur.com/FpkBn.jpg
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 WindowsFormsApplication2
{
public partial class MDI : Form
{
private int childFormNumber = 0;
public Form1 objfrmPalm;
public Form1 objMain;
public MDI()
{
InitializeComponent();
this.HorizontalScroll.Minimum = 0;
this.VerticalScroll.Maximum = 2000;
}
private void ShowNewForm(object sender, EventArgs e)
{
Form childForm = new Form();
childForm.MdiParent = this;
childForm.Text = "Window " + childFormNumber++;
childForm.Show();
}
private void OpenFile(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
string FileName = openFileDialog.FileName;
}
}
private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
string FileName = saveFileDialog.FileName;
}
}
private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void CutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void ToolBarToolStripMenuItem_Click(object sender, EventArgs e)
{
toolStrip.Visible = toolBarToolStripMenuItem.Checked;
}
private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
{
statusStrip.Visible = statusBarToolStripMenuItem.Checked;
}
private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.Cascade);
}
private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileVertical);
}
private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileHorizontal);
}
private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.ArrangeIcons);
}
private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form childForm in MdiChildren)
{
childForm.Close();
}
}
private void MDI_Load(object sender, EventArgs e)
{
}
#region mnufrmPage_Click
private void mnufrmPage_Click(object sender, EventArgs e)
{
objMain = new Form1();
objMain.MdiParent = this;
objMain.Show();
}
#endregion
#region mnuPalmWindow_Click
private void mnuPalmWindow_Click(object sender, EventArgs e)
{
objfrmPalm = new Form1();
objfrmPalm.MdiParent = this;
objfrmPalm.Size = new Size(369, 335);
objfrmPalm.l1 = new Label();
objfrmPalm.l1.AutoSize = false;
objfrmPalm.l1.Size = new Size(140, 73);
objfrmPalm.l1.Text = "";
objfrmPalm.l1.BackColor = Color.Transparent;
//objfrmPalm.l1.BorderStyle = BorderStyle.FixedSingle;
//objfrmPalm.Controls.Add(l1);
objfrmPalm.l1.Parent = objfrmPalm.pictureBox1;
objfrmPalm.pictureBox1.Controls.Add(objfrmPalm.l1);
objfrmPalm.l1.MouseMove += l1_MouseMove;
objfrmPalm.l1.MouseDown += l1_MouseDown;
objfrmPalm.l1.Paint += L1_Paint;
objfrmPalm.Show();
//frmPalmWindow objpalm = new frmPalmWindow();
//objpalm.MdiParent = this;
//objpalm.Show();
}
private void L1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.Red), new Rectangle(0, 0, ((Label)sender).Width - 1, ((Label)sender).Height - 1));
}
void l1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
objfrmPalm.MouseDownLocation = e.Location;
}
}
void l1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
objfrmPalm.l1.Left = e.X + objfrmPalm.l1.Left - objfrmPalm. MouseDownLocation.X;
objfrmPalm.l1.Top = e.Y + objfrmPalm.l1.Top - objfrmPalm.MouseDownLocation.Y;
objMain.AutoScroll = true;
objMain.AutoScrollPosition = new Point(Cursor.Position.X + e.X, Cursor.Position.Y + e.Y);
// this.Refresh();
//this.SetAutoScrollMargin(e.X, e.Y);
//myControl.SetDisplayRectLocation(
//myControl.DisplayRectangle.X,
//myControl.DisplayRectangle.Y + MouseWheelDelta * ScrollAmount );
//this.HorizontalScroll.Value = e.Y;
//this.VerticalScroll.Value = e.X;
// Point CurrentPoint;
// this.SetAutoScrollMargin(e.X, e.Y);
//this.AutoScrollPosition = new Point(Convert.ToInt32( Math.Abs(this.AutoScrollPosition.X)),Convert.ToInt32( Math.Abs(CurrentPoint.Y)));
//this.AutoScrollPosition = new Point(Convert.ToInt32(e.X + objfrmPalm.l1.Left - objfrmPalm.MouseDownLocation.X+100), Convert.ToInt32(e.Y + objfrmPalm.l1.Top - objfrmPalm.MouseDownLocation.Y+200));
//this.Refresh();
}
}
#endregion
private Point MouseDownLocation;
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
// label1.Left = e.X + label1.Left - MouseDownLocation.X;
// label1.Top = e.Y + label1.Top - MouseDownLocation.Y;
//// this.ScrollToControl(label1);
// this.AutoScrollPosition = new Point(Convert.ToInt32(e.X + label1.Left - this.MouseDownLocation.X + 100), Convert.ToInt32(e.Y + label1.Top - this.MouseDownLocation.Y + 200));
// this.Refresh();
}
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
//if (e.Button == System.Windows.Forms.MouseButtons.Left)
//{
// MouseDownLocation = e.Location;
//}
}
}
}
Please help me and if I missed something then please guide me.

C# Disjointed Link Labels Navigation for TabControl - How to highlight current tab open with link labels

Is it possible to get any value from the currently displayed tabcontrol that is open (displayed)? Trying to highlight the adjacent / corresponding tab / link label.
I am using link labels as navigation for the tabs. The real (ugly top) tabs will hidden when the project is finished.
//LINK LABELS CLICK EVENTS TO DISPLAY / OPEN TABS
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 0;
//COLOURS TO BE APPLIED WHEN THE CORRESPONDING TAB IS OPEN
linkLabel1.BackColor = Color.Black;
linkLabel1.ForeColor = Color.White;
linkLabel1.ActiveLinkColor = System.Drawing.Color.White;
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 1;
txtFirstName.Focus();
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 2;
}
After #Idle_Mind answer I still was not sure how to bind / wireup the event. This is for anyone else with same question:
//LINK LABELS CLICK EVENTS TO DISPLAY / OPEN TABS
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 0;
labels_LinkClicked(sender, e);
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 1;
txtFirstName.Focus();
labels_LinkClicked(sender, e);
}
private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
tabControl1.SelectedIndex = 2;
labels_LinkClicked(sender, e);
}
//METHOD TO CALL ON EACH CLICK OF LINK LABELS
private void labels_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
LinkLabel lbl = (LinkLabel)sender;
tabControl1.SelectedIndex = labels.IndexOf(lbl);
foreach (LinkLabel curLbl in labels)
{
curLbl.BackColor = (lbl == curLbl) ? Color.Black : Color.Transparent;
}
}
Wire up the LinkClinked() events to the same event handler like below:
private List<LinkLabel> labels;
private void Form2_Load(object sender, EventArgs e)
{
labels = new List<LinkLabel>() { linkLabel1, linkLabel2, linkLabel3 };
}
private void labels_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
LinkLabel lbl = (LinkLabel)sender;
tabControl1.SelectedIndex = labels.IndexOf(lbl);
foreach(LinkLabel curLbl in labels)
{
curLbl.BackColor = (lbl == curLbl) ? Color.Black : Color.Gray;
}
}

Creating unique event handlers for dynamically created buttons

I want to add buttons to my page dynamically. It will depend on the number of results from a SELECT statement. I
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < Query.length; i++)
{
Button btn = new Button();
btn.ID = "Button" + i;
btn.Click += new EventHandler(btn_Click());
btn.Text = i.ToString();
pagingPanel.Controls.Add(btn);
}
}
}
But I want each button to have it's own custom event handler. If I click one button, I want it do have a different result than if I click another. I would like to do something like this where I can pass an aditional parameter:
protected void btn_Click(object sender, EventArgs e, string test)
{
System.Diagnostics.Debug.WriteLine(test);
}
Perhaps I don't know which objects to pass? Or maybe I am approaching this the wrong way.
How do I achieve the desired results?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
// you do not use !IsPostBack here
//count of func must be equal with 'Query.Length'
string[,] arr ={
{"func1","hello world"},
{"func2","Hello ASP.NET"}
};
for (int i = 0; i < Query.Length; i++)//I assume length is 2
{
Button btn = new Button();
btn.ID = arr[i, 0];
btn.CommandArgument = arr[i, 1];
btn.Click += new EventHandler(btn_Click);
btn.Text = i.ToString();
pagingPanel.Controls.Add(btn);
}
}
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
System.Reflection.MethodInfo methodInfo = typeof(_Default2).GetMethod(btn.ID); //_Default2 is class name of code behind
if (methodInfo != null)
{
object[] parameters = new object[] { btn.CommandArgument};
methodInfo.Invoke(this,parameters);
}
}
public void func1(object args)
{
string test = args.ToString();
Response.Write(test);
}
public void func2(object args)
{
string test = args.ToString();
Response.Write(test);
}
First and foremost - you have to create buttons whether it is postback or not. The button click is the reason for the postback, if you don't have buttons - what will be clicking?
Second, add to your page class:
Dictionary<Button, ButtonInfo> fButtonLookup = new Dictionary<Button, ButtonInfo>();
Then, where you create buttons:
fButtonLookup.Clear();
for (int i = 0; i < Query.length; i++)
{
Button btn = new Button();
fButtonLookup.Add(btn, new ButtonInfo() { whatever information about this button you want to keep});
...
}
Then, in your button click:
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (fButtonLookup.ContainsKey(btn))
{
ButtonInfo info = fButtonLookup[btn];
// do waht you need with button information
}
}
You could just check sender to see which button was clicked:
protected void btn_Click(object sender, EventArgs e)
{
if (sender == btnOne)
performBtnOne("foo");
else if (sender == btnTwo)
performButtonTwo("bar");
}
To expand on itsme86...
protected void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender; //Now you have an instantiated version of the button pressed.
switch (btn.Name)
{
case "foo":
performBtnOne();
break;
case "bar":
performBtnTwo();
break;
default:
performUnexpectedButton();
break;
}
}

How to handle Windows Forms controls created at runtime?

I have a Form on which there are two controls, a Button and a TextBox.
These controls are created at runtime.
When I click the Button, I want to do some operations with the TextBox.Text property.
But, with this code I can't:
private void Form1_Load(object sender, EventArgs e)
{
TextBox txb = new TextBox();
this.Controls.Add(txb);
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
Here I'm trying to find it:
public void btn_Click(object sender, EventArgs e)
{
foreach (var item in this.Controls)
{
if (item is TextBox)
{
if (((TextBox)item).Name=="txb")
{
MessageBox.Show("xxx");
}
}
}
}
You don't have a Textbox with Name "txb". so, this expression will always be false: if(((TextBox)item).Name=="txb")
try this codes:
private void Form1_Load(object sender, EventArgs e)
{
TextBox txb = new TextBox();
txb.Name = "txb";
this.Controls.Add(txb);
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
I would save off a reference to your TextBox.
TextBox txb;
private void Form1_Load(object sender, EventArgs e)
{
txb = new TextBox();
this.Controls.Add(txb);
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}

Categories