Select part of Button's text - c#

I'm using this code to create buttons with two lines text
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
int n = 0;
int s = 99;
for (int i = 0; i < 20; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
panel1.Controls.Add(button); // here
button.Size = new Size(50, 50);
if (i == 4 || i == 9||i==14||i==19)
{
top = 30;
left = 23;
top +=button.Top+2;
left += button.Width+2;
}
else
left += button.Width + 2;
n = n + 1;
s = s + 1;
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Click += Button_Click;
}
}
private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(s);
}
So I need to select only second line brom my button text when I click dynamic button. How will I do this?

you can store some data in Tag property:
button.Text = Convert.ToString(n) + Environment.NewLine + Convert.ToString(s);
button.Tag = new int[] { n, s };
and later retrive it and use:
private void Button_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
var data = button.Tag as int[];
string s = data[1].ToString();
MessageBox.Show(s);
}

private void Button_Click(object sender, EventArgs e)
{
string s;
Button button = (Button)sender;
s = button.Text + Environment.NewLine;
MessageBox.Show(button.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None)[1]);
}

Related

Labels don't move using Mouse events

I created 5 labels using a for. Inside the for I declared the properties of the labels, such as location, size, color, etc. and the possibility to move the labels using the mouse events:
private void Form1_Load(object sender, EventArgs e)
{
int alto = 100;
int ancho = 65;
for (byte fila = 0; fila < 5; fila++)
{
Label letras = new Label();
letras.Height = alto;
letras.Width = ancho;
letras.BackColor = Color.Blue;
letras.ForeColor = Color.AntiqueWhite;
letras.Font = new Font("Arial", 60);
letras.TextAlign = ContentAlignment.MiddleCenter;
letras.BorderStyle = BorderStyle.FixedSingle;
letras.Left = 200 + (ancho + 20) * fila;
letras.Top = 60;
letras.Text = null;
letras.MouseDown += new MouseEventHandler(this.letras_MouseDown);
letras.MouseMove += new MouseEventHandler(this.letras_MouseMove);
letras.MouseUp += new MouseEventHandler(this.letras_MouseUp);
this.Controls.Add(letras);
}
}
Later in the code, I create the events which will make the labels move.
private void letras_MouseDown(object sender, MouseEventArgs e)
{
mousedown = true;
}
private void letras_MouseMove(object sender, MouseEventArgs e)
{
if (mousedown)
{
letras.Location = new Point(letras.Location.X + e.Location.X, letras.Location.Y + e.Location.Y);
}
}
private void letras_MouseUp(object sender, MouseEventArgs e)
{
mousedown = false;
}
but it isn't working. Any ideas? I think that could be an Indentation problem, but I'm not sure.
The sender argument received by the letras_MouseMove method is the Label so the first thing to do is perform a cast to a usable Label object. Then simply test the static Control.MouseButtons property to determine if the Left button is currently active. You calculated the offset correctly. I believe that all you really needed was to have the correct Label object. (Of course I tested it)
Some of the code you posted is not necessary and should be removed. This shows a minimal working example.
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// This code stays the same
int alto = 100;
int ancho = 65;
for (byte fila = 0; fila < 5; fila++)
{
Label letras = new Label();
letras.Height = alto;
letras.Width = ancho;
letras.BackColor = Color.Blue;
letras.ForeColor = Color.AntiqueWhite;
letras.Font = new Font("Arial", 60);
letras.TextAlign = ContentAlignment.MiddleCenter;
letras.BorderStyle = BorderStyle.FixedSingle;
letras.Left = 200 + (ancho + 20) * fila;
letras.Top = 60;
letras.Text = null;
letras.MouseMove += new MouseEventHandler(this.letras_MouseMove);
this.Controls.Add(letras);
}
}
// This code is different
private void letras_MouseMove(object sender, MouseEventArgs e)
{
Label letra = (Label)sender;
if(MouseButtons == MouseButtons.Left)
{
// Here, your original calculation works OK once you have the correct Label object
letra.Location = new Point(letra.Location.X + e.Location.X, letra.Location.Y + e.Location.Y);
}
}
}
Haven't tested but replace:
private void Form1_Load(object sender, EventArgs e)
{
int alto = 100;
int ancho = 65;
for (byte fila = 0; fila < 5; fila++)
{
letras = new Label();
With:
Label[] labels = Array.Empty<Label>();
private void Form1_Load(object sender, EventArgs e)
{
int alto = 100;
int ancho = 65;
for (byte fila = 0; fila < 5; fila++)
{
labels[fila] = new Label();
And replace every letras in the file with labels[(number)].

select/deselect button in asp.net by last selected first deselect

I have dynamically created buttons as shown in code all all the button from 10:00 to 12:00 with 15 min of interval and deselect in lifo order like if i have selected 10:0 and 10:15 then i can not select 10:45 .. and i i have selected 10:0,10:15,10:30,10:45 and then i have to deselect 10:15 then first we have to deselect 10:30 and 10:45 ...please help me out.
private void GetControls()
{
count++;
for (int i = 10; i < 12; i++)
{
for (int j = 0; j < 60; j += 15)
{
Button btn = new Button();
btn.Text = i + "-" + j;
btn.ID = i + "-" + j;
btn.Command += new CommandEventHandler(this.btn_Click);
// btn.Click += btn_Click;
flag = true;
btn.CommandName = i + "-" + j;
if (count==1)
{
PlaceHolder1.Controls.Add(btn);
}
}
}
}
private void btn_Click(object sender, CommandEventArgs e)
{
count++;
string ID = (sender as Button).ID;
Label1.Text = " Congrates! Your meeting time has been sheduled upto " + ID;
Label1.Visible = false;
Button btn = sender as Button;
if (btn.BackColor == Color.Green)
{
btn.BackColor = System.Drawing.Color.Yellow;
getStatus(sender);
}
else
{
btn.BackColor = System.Drawing.Color.Green;
}
Correct me if I am wrong! You want to only select one button at a time so that if one button is clicked, the rest should reset? if that's the case, here's a code to do so:
[Edit]
Added a Session to remember dynamic button ids and used (.) instead of (-) for button Ids
private void GetControls()
{
count++;
for (int i = 10; i < 12; i++)
{
for (int j = 0; j < 60; j += 15)
{
Button btn = new Button();
btn.Text = i + "-" + j;
btn.ID = i + "." + j;
btn.Command += new CommandEventHandler(this.btn_Click);
// btn.Click += btn_Click;
flag = true;
btn.CommandName = i + "-" + j;
if (count == 1)
{
PlaceHolder1.Controls.Add(btn);
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
if (!createdControls.Contains(btn.ID)) createdControls.Add(btn.ID);
Session["Controls"] = createdControls;
}
}
}
}
[Edited] Replace the btn-Click event with the following.
private void btn_Click(object sender, CommandEventArgs e)
{
count++;
string ID = (sender as Button).ID;
ResetButton(Convert.ToDouble(ID));
Label1.Text = " Congrates! Your meeting time has been sheduled upto " + ID;
Button btn = sender as Button;
if (btn.BackColor == Color.Green)
{
btn.BackColor = System.Drawing.Color.Yellow;
}
else
{
btn.BackColor = System.Drawing.Color.Green;
}
}
[Edited] And this is the method implementation
private void ResetButton(double selectedButtonID)
{
List<string> createdControls = Session["Controls"] != null ? Session["Controls"] as List<string> : new List<string>();
TimeSpan timespan = TimeSpan.FromHours(selectedButtonID);
string currentSelectedTime = timespan.ToString("h\\:mm");
foreach (string buttonID in createdControls)
{
if (!string.IsNullOrEmpty(buttonID))
{
int comparisonResult = timespan.CompareTo(TimeSpan.FromHours(Convert.ToDouble(buttonID)));
Button button = Page.FindControl(buttonID) as Button;
if (button != null && comparisonResult==1)
{
button.BackColor = Color.Yellow;// selected
}
else
{
button.BackColor = Color.Red;// deselected
}
}
}

dynamically adding buttons and button objects in panel

private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
int h = Convert.ToInt32(a);
for (int i = 0; i <= h; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(60, 23);
buttonArray[i].Location = new Point(40,20);
panel1.Controls.Add(buttonArray[i]);
}
}
my task is if user enter 3 in text box. 3 buttons should be created dynamically and added to panel how to do that?????? i am using button array please suggest me
For example you can use this.
private void button1_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
string a = textBox1.Text;
int h = Convert.ToInt32(a);
for (int i = 0; i <= h; i++)
{
var btn = new Button {Size = new Size(60, 23), Dock=DockStyle.Left, Text=h.ToString() };
btn.Click+= delegate(object sender, EventArgs e) { //your commands };
panel1.Controls.Add(btn);
}
}
In this post already answered a similar question:
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
int h = Convert.ToInt32(a);
for (int i = 0; i <= h; i++)
{
var b = new Button { Size = new Size(60, 23), Location = new Point(4 + i * 57, 20), Text = string.Format("button{0}", i) };
b.Click += b_Click;
panel1.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
it is desirable to test the validator to always have been a number
string a = textBox1.Text;
May be using a List is more situable?
List<Button>Buttons=new List<Buttons>();
private void button1_Click(object sender, EventArgs e)
{
Buttons.Clear();
string a = textBox1.Text;
//here should be checking if "a" is digit and is not empty
int h = Convert.ToInt32(a);
for (int i = 0; i <= h; i++)
{
Button btn=new Button();
btn.Parent=panel1;
btn.Size=new Size(60, 23);
btn.Location = new Point(40,5+25*i); //arrange verically
btn.Text = "Button "+i.ToString();
btn.Click+=btn_Click;
btn.Tag="Some Value you want to restore after button click";
Buttons.Add(btn)
}
}

Button Click Frequency Array

I need to make a ListBox that displays how often a Button is clicked.
The user chooses how many buttons are available to click. Here is what I've tried:
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
for (int i = 0; i < freq_array[clicked]; i++)
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
freq_array uses the 'clicked' variable to add to the frequency that button has been clicked. Or, it's supposed to.
When I debug it, 'clicked' always comes out to 0. I want 'clicked' to equal the text value of the button that's clicked. When I try to run the program, I get an error saying "Input string was not in correct format."
Edit:
I was able to fix my program with help from you guys. I realized I didn't show enough of my code to be clear enough, and I apologize for that. I had to add some things and move things around and got it soon enough. Thank you all.
Here is the code just for those who may need help in the future:
public partial class Form1 : Form
{
int[] freq_array = new int[11];
int[] numList = new int[11];
int oBase = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
invisiblity();
}
private void invisiblity()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
ctrl.Visible = false;
}
}
private void btnSetBase_Click(object sender, EventArgs e)
{
Form2 frmDialog = new Form2();
frmDialog.ShowDialog(this);
if (frmDialog.DialogResult == DialogResult.OK)
{
oBase = frmDialog.Base;
//lblOutDigits.Text = oBase.ToString();
for (int i = 0; i < oBase; i++)
{
numList[i] = i;
}
}
ShowBaseButtons(oBase);
}
private void ShowBaseButtons(int last_digit)
{
invisiblity();
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
if (int.Parse(ctrl.Text) <= last_digit - 1)
ctrl.Visible = true;
}
}
private void btnN_Click(object sender, EventArgs e)
{
lblOutDigits.Text += ((Button)(sender)).Text;
int clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
}
private void btnShowFreq_Click(object sender, EventArgs e)
{
lstFrequencies.Items.Clear();
for (int i = 0; i < oBase; i++)
lstFrequencies.Items.Add(numList[i] + " \t\t\t" + freq_array[i]);
}
Your code should work as long as your Button Text is actually just a number. Since what you are trying to do is create an index, what I usually do is use the Tag Property of the control, set it to the Index I want in the designer and then cast that to an Int.
i.e.
if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
freq_array[clicked]++;
I believe what is happening is that you are not initializing your ListBox, This example Code does work using your initial method. Just create a new Form and paste it in and test.
public partial class Form1 : Form
{
ListBox lstFrequencies = new ListBox();
int[] freq_array = new int[10];
public Form1()
{
InitializeComponent();
Size = new Size(400, 400);
lstFrequencies.Location = new Point(150, 0);
lstFrequencies.Size = new Size(150, 200);
Controls.Add(lstFrequencies);
int top = 0;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Size = new Size(70, 30);
btn.Location = new Point(5, top);
Controls.Add(btn);
top += 35;
btn.Tag = i;
btn.Text = i.ToString();
btn.Click += new EventHandler(btn_Click);
lstFrequencies.Items.Add(i.ToString());
}
}
void btn_Click(object sender, EventArgs e)
{
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked]; //Cleaned up you do not need to iterate your list
// Using my example code
//if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
//{
// freq_array[clicked]++;
// lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
//}
}
}
Your code always comes out to 0 because you never assign last clicked value to button text. Try this code:
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
clicked = Convert.ToInt32(((Button)sender).Text);
lstFrequencies.Items.Add(((Button)sender).Name + " " + ++clicked);
button1.Text = clicked.ToString(); // you lose this line
}
EDIT: Counter from variable member
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
// if you want to display button name, change .Text to .Name
lstFrequencies.Items.Add(((Button)sender).Text + " " + ++clicked);
}

Add Event at runtime

my method is :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 10; i++)
{
Button btn = new Button();
btn.Name = "btn" + i.ToString();
btn.Text = "btn" + i.ToString();
btn.Click += new EventHandler(this.btn_Click);
this.flowLayoutPanel1.Controls.Add(btn);
}
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
if (btn.Name == "btn1")
{
this.Text = "stack";
}
}
There is a better approach ?
The code you used:
btn.Click += new EventHandler(this.btn_Click);
Is the correct code to add the handler. Creating the buttons and adding them to their container looks good.
The only thing I would add is just make sure you are creating the controls on postback too, prior to viewstate being restored, so that the events can actually be called.
Or maybe:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 10; i++)
{
Button btn = new Button();
btn.Text = "btn" + i.ToString();
btn.Tag = i;
btn.Click += delegate
{
if ((int)btn.Tag == 1)
this.Text = "stack";
};
this.flowLayoutPanel1.Controls.Add(btn);
}
}

Categories