I have 2 textbox and 1 button textbox1,textbox2 and 1 increment button.Both textbox is initialize by 1.If i will click on textbox1 and then click on incr button the value belongs to textbox1 will be increase only.And whenever i will click on textbox2 and again i will click on incr button only textbox2 value will be increment.
How will i do this?
You didn't say whether you were in WinForms or in WPF, so I won't show any code.
Have a field TextBox activeTextBox in your class. In the GotFocus events of each textbox, set activeTextBox = this text box. In the button click, convert activeTextBox's text to an integer, add one, and convert back to string and set the text back.
Edit:
activeTextBox is a field you will need to set up, the designer won't make it for you. If you set the GotFocus event of textBox1 set activeTextBox = textBox1, and similar for textBox2, then activeTextBox will always have the 'current' text box. Then in the button's click event, you can do whatever you need to do on activeTextBox. You shouldn't need to access textBox1 or textBox2 from the button click handler at all.
This can be done on the client side using javascript. On focus of textbox1 update a hiddenfield value. similarly for the textbox2. then on button click, based on hidden f
Create a windows form application and paste this code on 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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
TextBox textbox1 = new TextBox(), textbox2 = new TextBox();
Button button1 = new Button();
int FocusedTextBox = 0;
public Form1()
{
InitializeComponent();
this.Load += new System.EventHandler(this.Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
textbox1.Text = textbox2.Text = "1";
textbox1.Location = new Point(100, 100);
textbox2.Location = new Point(100, 140);
button1.Location = new Point(100, 180);
textbox1.Click += new EventHandler(textbox1_Click);
textbox2.Click += new EventHandler(textbox2_Click);
textbox1.ReadOnly = true;
textbox2.ReadOnly = true;
this.Controls.Add(textbox1);
this.Controls.Add(textbox2);
this.Controls.Add(button1);
}
void textbox2_Click(object sender, EventArgs e)
{
FocusedTextBox = 2;
}
void textbox1_Click(object sender, EventArgs e)
{
FocusedTextBox = 1;
}
void button1_Click(object sender, EventArgs e)
{
if (FocusedTextBox ==1)
textbox1.Text = (int.Parse(textbox1.Text) + 1).ToString();
else if (FocusedTextBox == 2)
textbox2.Text = (int.Parse(textbox2.Text) + 1).ToString();
}
}
}
private int pickedbox = 0
[...]
private void textBox1_Enter(...)
{
pickedbox = 0;
}
private void textBox2_Enter(...)
{
pickedbox = 1;
}
private void button1_Click(...)
{
switch(pickedbox)
{
case 0:
textBox1.Text = int.Parse(textBox1.Text)++;
break;
case 1:
textBox2.Text = int.Parse(textBox2.Text)++;
break;
}
}
if (textBox1.Focused)
{
textBox1.Text = (Convert.ToInt32(textBox1.Text) + 1) + "";
}
else if (textBox2.Focused)
{
textBox2.Text = (Convert.ToInt32(textBox2.Text) + 1) + "";
}
else if (textBox3.Focused)
{
textBox3.Text = (Convert.ToInt32(textBox3.Text) + 1) + "";
}
But ".Focused" is always returing False.
Why ?
Related
Stack overflow! I've been here multiple times and I've always managed to find an answer to my questions! But now I come forward with a problem that I can't find the solution for, Heres a bit of c# that generates a new TextBox when you press a button, How do I move the text box after its creation?
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int cLeft = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddNewTextBox();
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = cLeft * 25;
txt.Left = 100;
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
return txt;
}
}
}
To access the dynamic controls on a form, use the controls collection. For this example I added a new button on the form which moves all the text boxes on the form.
private void btnMove_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls) // all controls on form
{
if (c is Button) continue; // don't move buttons
if (c is System.Windows.Forms.TextBox) // move textboxes
c.Top += 1; // move down 1 pixel
c.Left += 1; // move right 1 pixel
}
}
I managed to get a clear button on a TextBox line with little code. This deletes the corresponding line and itself when clicking. But the button appears only once. It should be generated with each click on each additional line. Can someone help me there? Many Thanks.
Is WinForm VS2010 C#
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 Daten_zu_TextBox_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn";
btn1.Click += new EventHandler(btn1_Click);
btn1.Size = new Size(18, 18);
btn1.Text = "X";
btn1.ForeColor = Color.Red;
textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline1");
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
void btn1_Click(object sender, EventArgs e)
{
textBox1.Controls.Clear();
textBox1.Text = textBox1.Text.Remove(1, textBox1.Lines[0].Length + 0 );
textBox1.Text = textBox1.Text.Remove(0, textBox1.Lines[0].Length + 0);
}
}
}
private int ButtonCount2 = 0;
private int Btn2Y = 18;
private void button2_Click(object sender, EventArgs e)
{
Button btn2 = new Button();
btn2.Name = "btn2" + ButtonCount2;
btn2.Click += new EventHandler(btn2_Click);
btn2.Size = new Size(18, 18);
btn2.Location = new Point(1, Btn2Y * ButtonCount2);
ButtonCount2++;
btn2.Text = "X";
btn2.ForeColor = Color.Red;
textBox2.Controls.Add(btn2);
string sent = ("\t" + "Testline" + ButtonCount2);
textBox2.AppendText(sent);
textBox2.AppendText(Environment.NewLine);
}
void btn2_Click(object sender, EventArgs e)
{
var bt2 = sender as Button;
var bt2Id = textBox2.Controls.IndexOf(bt2);
textBox2.Controls.Remove(bt2);
var lines = textBox2.Text.Replace("\r\n", "\n").Split('\n').ToList();
lines.RemoveAt(bt2Id);
textBox2.Text = string.Join("\r\n", lines);
foreach (Button btn2 in textBox2.Controls)
{
var Id2 = int.Parse(btn2.Name.Replace("btn2", ""));
if (Id2 > bt2Id)
{
var b2 = textBox2.Controls.Find(btn2.Name, false)[0];
var loc2 = btn2.Location;
b2.Location = new Point(loc2.X, loc2.Y - Btn2Y);
}
}
ButtonCount2--;
}
The second button looks like this.
You're putting all the X buttons on the same place, on top of textbox. Implement some logic that increases Y location of your button. That can be something like this:
//... your code here ...
btn1.ForeColor = Color.Red;
//increase Y
// for each control that is inside of textBox,
// lower your newly created button by count * 18
// so that btn1.Top will be 0, 18, 36 etc...
btn1.Top = textBox1.Controls.Count * 18;
textBox1.Controls.Add(btn1);
also, as WPFUser noticed, on click on X button, you're removing all the X buttons. I'm guessing you should remove last, bottom one
EDIT 2. Each button should remove its corresponding line, like this (didn't test it :))
void btn1_Click(object sender, EventArgs e)
{
//remove right line
text1.Text = text1.Lines[text1.Controls.IndexOf((Control)sender)].Remove(0);
//remove button
text1.Controls.Remove(text1.Controls.OfType<Button>().Last());
}
#jadolo ,Your code is correct ,It add new button every time but every button will located at same location so those all button will not visible to you, Add assign location property of button like this,so all button are displayed correctly.
Form1.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
int i = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void btn1_Click(object sender, EventArgs e)
{
textBox1.Controls.Clear();
textBox1.Text = textBox1.Text.Remove(1, textBox1.Lines[0].Length + 0);
textBox1.Text = textBox1.Text.Remove(0, textBox1.Lines[0].Length + 0);
}
private void button1_Click_1(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn"+i++;
btn1.Click += new EventHandler(button1_Click_1);
btn1.Size = new Size(18,18 );
btn1.Text = "X";
btn1.Location = new Point(0, i);
i += 18;
btn1.ForeColor = Color.Red;
this.textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline1");
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
}
}
Design :
Output :
I hope this will help you.
Below is tested working codes. The button will coincide with text for the textbox font size being the default 8.
private int ButtonCount = 0;
private int BtnY = 13;
private void button1_Click(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn" + ButtonCount;
btn1.Click += new EventHandler(btn1_Click);
btn1.Size = new Size(18, 18);
btn1.Location = new Point(1, BtnY * ButtonCount);
btn1.Tag = ButtonCount; // the last edit
ButtonCount++;
btn1.Text = "X";
btn1.ForeColor = Color.Red;
textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline" + ButtonCount);
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
void btn1_Click(object sender, EventArgs e)
{
var bt = sender as Button;
var btId = textBox1.Controls.IndexOf(bt);
textBox1.Controls.Remove(bt);
var lines = textBox1.Text.Replace("\r\n", "\n").Split('\n').ToList();
lines.RemoveAt(btId);
textBox1.Text = string.Join("\r\n", lines);
foreach (Button btn in textBox1.Controls)
{
//var Id = int.Parse(btn.Name.Replace("btn", "")); // the last edit
var Id = (int)btn.Tag; // the last edit
if (Id > btId)
{
var b = textBox1.Controls.Find(btn.Name, false)[0];
var loc = btn.Location;
b.Location = new Point(loc.X, loc.Y - BtnY);
}
}
ButtonCount--;
}
i need to use a button to make a number of textboxes with related buttons each button will add 1 to the textbox (that i want to be related to it HOW?)
i have a windows form with button1 and three panels
==========================================
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace AdvancedCounter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (panel3.Controls != null)
{
var btn = panel3.Controls.Find("_B", true).First();
btn.Click += new EventHandler(Btn_Click);
}
}
int a = 0;
int counter=0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
Button btn = new Button();
btn.Location = new Point(0, 100);
btn.Text = "ADD";
btn.Name ="_B";
btn.Dock = DockStyle.Left;
btn.Click += new EventHandler(Btn_Click);
TextBox txt = new TextBox();
txt.Name = "_T";
txt.Location = new Point(500, 100);
txt.Dock = DockStyle.Left;
txt.Text = a.ToString();
panel3.Controls.Add(txt);
panel3.Controls.Add(btn);
foreach (var item in panel3.Controls.Find("_B", true))
{
item.Text = "ass";
}
}
private void Btn_Click(object sender, EventArgs e)
{
// MessageBox.Show(sender.ToString());
// throw new NotImplementedException();
var txtbx= panel3.Controls.Find("_T", true).First();
var btnbx = panel3.Controls.Find("_B", true).First();
a++;
// find[1].Dispose();
txtbx.Text = a.ToString();
}
}
}
First you are giving same Name property for every TextBox and Button, you should not do that. Instead do like this for example:
btn.Name = "_B_"+ counter;
So you will have different Name for Buttons and TextBoxes. And in event handler:
private void Btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string index = btn.Name.Split('_')[2];
string tbName = "_T_" + index;
var txtbx= panel3.Controls.Find(tbName, true).First();
a++;
txtbx.Text = a.ToString();
}
I have a simple TextBox:
<TextBox Name="PART_txtBx" IsReadOnly="True" ScrollViewer.VerticalScrollBarVisibility="Auto" />
and from codebehind i add some text every while:
public MainWindow()
{
InitializeComponent();
DispatcherTimer dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(100);
dt.Tick += dt_Tick;
dt.Start();
}
void dt_Tick(object sender, EventArgs e)
{
PART_txtBx.Text += "hi\n";
}
when i click on the textbox it automatically put the scrollbar on top when i add some text to it.
if I handle the PreviewMouseLeftButtonDown event like this:
private void PART_txtBx_PreviewMouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
the textbox works normally but i can't (of course) select any text.
any ideas to prevent this behavior?
EDIT 1:
I noticed when the textbox is created there isn't any caret in it even if it has got focus. the caret is shown only when the click is executed but i can't find what's changed inside the textbox after the click.
My TextBox is read only so i don't need the caret.
May: PART_txtBx.CaretIndex =PART_txtBx.Length;
or:
PART_txtBx.SelectionStart = PART_txtBx.Text.Length;
PART_txtBx.ScrollToCaret();
ScrollToEnd().
with textbox_changed event
You need to extend your TextBox control to add PreviewTextChanged event, like it is described here. On PreviewTextChanged you will have to remember SelectionStart and SelectionLength
Handle event ScrollViewer.ScrollChanged for your TextBox:
ScrollViewer.ScrollChanged="OnScrollChanged" <!--in xaml-->
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
// here you could prevent scrolling
isOnBottom = (sender as TextBox).VerticalOffset + (sender as TextBox).ViewportHeight == (sender as TextBox).ExtentHeight;
}
Handle TextChanged event:
TextChanged="OnTextChanged"
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (isOnBottom) (sender as TextBox).ScrollToEnd();
// and here you can select text that was selected earlier
// by using remembered SelectionStart and SelectionLength
}
In the case of manual text entering you will have to prevent text selection
Hope, it helps
So i created my own CustomTextblock for resolving this issue:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace CE.EthernetMessagesManager.Views
{
public class CustomTextBox : TextBox
{
private int realCaretIndex = 0;
private bool triggeredByUser = false;
private bool isScrollingWithMouse = false;
public CustomTextBox()
: base()
{
this.PreviewMouseLeftButtonDown += CustomTextBox_PreviewMouseLeftButtonDown;
this.PreviewMouseLeftButtonUp += CustomTextBox_PreviewMouseLeftButtonUp;
this.PreviewMouseMove += CustomTextBox_PreviewMouseMove;
this.PreviewMouseWheel += CustomTextBox_PreviewMouseWheel;
this.TextChanged += CustomTextBox_TextChanged;
this.LostFocus += CustomTextBox_LostFocus;
this.AddHandler(ScrollViewer.ScrollChangedEvent, new RoutedEventHandler((X, S) =>
{
if ((S as ScrollChangedEventArgs).VerticalChange != 0 && triggeredByUser)
{
TextBox textBox = (X as TextBox);
int newLinePosition = 0;
newLinePosition = (int)(((S as ScrollChangedEventArgs).VerticalChange + textBox.ExtentHeight) / (textBox.FontSize + 2));
realCaretIndex += newLinePosition * ((S as ScrollChangedEventArgs).VerticalChange < 0 ? -1 : 1);
if (realCaretIndex < 0)
realCaretIndex = 0;
textBox.CaretIndex = realCaretIndex;
triggeredByUser = false;
}
}));
}
void CustomTextBox_LostFocus(object sender, System.Windows.RoutedEventArgs e)
{
e.Handled = true;
}
void CustomTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
TextBox textBox = sender as TextBox;
textBox.CaretIndex = realCaretIndex;
var max = (textBox.ExtentHeight - textBox.ViewportHeight);
var offset = textBox.VerticalOffset;
if (max != 0 && max == offset)
this.Dispatcher.Invoke(new Action(() =>
{
textBox.ScrollToEnd();
}),
System.Windows.Threading.DispatcherPriority.Loaded);
}
void CustomTextBox_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
{
triggeredByUser = true;
}
void CustomTextBox_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (isScrollingWithMouse)
{
TextBox textBox = sender as TextBox;
realCaretIndex = textBox.GetCharacterIndexFromPoint(Mouse.GetPosition(textBox), true);
}
}
void CustomTextBox_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
isScrollingWithMouse = false;
}
void CustomTextBox_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
TextBox textBox = sender as TextBox;
realCaretIndex = textBox.GetCharacterIndexFromPoint(Mouse.GetPosition(textBox), true);
triggeredByUser = true;
isScrollingWithMouse = true;
}
}
}
this CustomTextBox also pin the scrollbar to the bottom when i manually put it to bottom.
the xaml:
<v:CustomTextBox
IsReadOnly="True"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
/>
Sadly with this implementation selection is broken. I'll look into it
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);
}