How to dynamically add or remove textboxes? - c#

I would like to make a tool on my form that would allow the user to add or remove textboxes using a [+] and [-] button. This should only be possible if the items "*.doc" or "*.docx" are selected in a ComboBox.
I have tried this for the .doc thingy:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmbExtension.Text)
{
case "Other...":
string extensionName = Interaction.InputBox("Enter the new extension's name (for example *.txt): ", "New extension!");
File.AppendAllText(strPath, "\n" + extensionName);
// string extensionFunction = Interaction.InputBox("Enter the type of file it's supposed to be (for example Microsoft Word 2016): ", "Give us an idea.");
cmbExtension.Items.Clear();
LoadLines();
break;
case "*.doc":
btnPlus.Show();
break;
case "*.docx":
btnPlus.Show();
break;
default:
btnPlus.Hide();
break;
}
// As well as using similar code in these things, now empty:
if (cmbExtension.Text == "Other...")
{
}
if (cmbExtension.Text == "*.doc" || cmbExtension.Text == "*.docx")
{
}
}

You can use a FlowLayoutPanel in which you add and remove the textboxes.
To add a TextBox to a FlowLayoutPanel (or any container control) use:
TextBox textBox = new TextBox();
this.flowLayoutPanel1.Controls.Add(textBox);
To remove the last added TextBox from FlowLayoutPanel (or any container control) use:
int count = this.flowLayoutPanel1.Controls.Count;
if (count > 0)
{
this.flowLayoutPanel1.Controls[count - 1].Dispose();
}
Hear is an simple example with:
A FlowLayoutPanel with FlowDirection set to TopDown
Two buttons named btnPlus and btnMinus
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
cmbExtension.Items.Add("*.doc");
cmbExtension.Items.Add("*.docx");
cmbExtension.Items.Add("Other...");
btnPlus.Hide();
btnMinus.Hide();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cmbExtension.Text)
{
case "Other...":
// ...
btnPlus.Hide();
btnMinus.Hide();
break;
case "*.doc":
btnPlus.Show();
btnMinus.Show();
break;
case "*.docx":
btnPlus.Show();
btnMinus.Show();
break;
default:
btnPlus.Hide();
btnMinus.Hide();
break;
}
}
private void btnPlus_Click(object sender, EventArgs e)
{
TextBox textBox = new TextBox();
this.flowLayoutPanel1.Controls.Add(textBox);
}
private void btnMinus_Click(object sender, EventArgs e)
{
int count = this.flowLayoutPanel1.Controls.Count;
if (count > 0)
{
this.flowLayoutPanel1.Controls[count - 1].Dispose();
}
}
}
Snapshots:

Related

Display an alert message if a checkbox is uncheck C#

I'm trying to create a design form in visual studio with 4 checkboxes and I really want to make the user to check only one of them, and if he's not checked one, when he will press a button, he should receive a notification with the obligation to select a box, and the program should not starting.
RadioGroup is a control very similar in appearance to CheckBox. It's used to select only one RadioGroup in each group. You can define groups of radio buttons puttin inside a container (a Form, a Panel, a GroupBox). Add 4 radio buttons to your form, set the Text property.
You can check if a radio button is selected:
var isChecked = radioButton1.Checked;
Or make a method like this:
private int GetSelectedRadioIndex()
{
var buttons = new[]
{
this.radioButton1,
this.radioButton2,
this.radioButton3,
this.radioButton4
};
for (int i = 0; i < buttons.Length; i++)
{
if (buttons[i].Checked)
{
return i;
}
}
return -1;
}
If you get a <0 index, there aren't a radio selected. In other case you have a 0 index of the radio that is selected.
As indicated, use a container like a Panel or GroupBox while with a GroupBox you can set a caption to indicate what the RadioButtons are for.
Create a private list in the form
private List<RadioButton> _radioButtons;
Subscribe to the Form's OnShown event, add the following code where OptionsGroupBox is a GroupBox with four Radio Buttons. This ensures no default selection which is optional.
private void OnShown(object sender, EventArgs e)
{
_radioButtons = OptionsGroupBox.Controls.OfType<RadioButton>().ToList();
_radioButtons.ForEach(rb => rb.Checked = false);
}
Add a button to assert/get their selection.
private void CheckSelectionButton_Click(object sender, EventArgs e)
{
var selection = _radioButtons.FirstOrDefault(x => x.Checked);
if (selection == null)
{
MessageBox.Show("Make a selection");
}
else
{
MessageBox.Show($"You selected {selection.Text}");
}
}
Edit: Working with both Panel and GroupBox
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace RadioButtonApp
{
public partial class Form1 : Form
{
private List<RadioButton> _radioButtonsGroupBox;
private List<RadioButton> _radioButtonsPanel;
public Form1()
{
InitializeComponent();
Shown += OnShown;
}
private void OnShown(object sender, EventArgs e)
{
_radioButtonsGroupBox = OptionsGroupBox.Controls.OfType<RadioButton>().ToList();
_radioButtonsGroupBox.ForEach(rb => rb.Checked = false);
_radioButtonsPanel = OptionsPanel.Controls.OfType<RadioButton>().ToList();
_radioButtonsPanel.ForEach(rb => rb.Checked = false);
}
private void CheckSelectionInGroupBoxButton_Click(object sender, EventArgs e)
{
var selection = _radioButtonsGroupBox.FirstOrDefault(x => x.Checked);
if (selection == null)
{
MessageBox.Show("Make a selection");
}
else
{
MessageBox.Show($"You selected {selection.Text}");
}
}
private void CheckSelectionInPanelButton_Click(object sender, EventArgs e)
{
var selection = _radioButtonsPanel.FirstOrDefault(x => x.Checked);
if (selection == null)
{
MessageBox.Show("Make a selection");
}
else
{
MessageBox.Show($"You selected {selection.Text}");
}
}
}
}

How to make label text(number) change by clicking checkbox?

Teacher gave us an assignment. Checkboxes are lessons that students may choose and labels under them are the free spots left. Basically everytime a lesson(checkbox) selected the number connected to it at label should lessen minus 1. if person unchecks it, number should return to basic.
Sorry for my English, i hope it's understandable.
You can try to subscribe to the CheckedChanged event for each checkbox. And use Convert.ToInt32 Method to get the value in labels. Then judge the checkbox selected via swicth statement.
public Form1()
{
InitializeComponent();
checkBox1.CheckedChanged += checkBox_CheckedChanged;
checkBox2.CheckedChanged += checkBox_CheckedChanged;
checkBox3.CheckedChanged += checkBox_CheckedChanged;
}
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) + 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) + 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) + 1).ToString();
break;
}
}
else
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) - 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) - 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) - 1).ToString();
break;
}
}
}
That's an example where I picked the checkedchanged property of each of the checkboxs and this is the function in each of them. you can change the initial value or the changed value as you want by changing the 0 or the ++ or the --. You just add the two if conditions from each function to your function and change the name in them to reflect the name of your label.
public partial class Form1 : Form
{
int counter=0;
public Form1()
{
InitializeComponent();
label1.Text = counter.ToString();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox1.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox3.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox2.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
}

Hiding GroupBoxes depending on selected index of combo box

I'm trying to display / hide a 2 combo boxes depending on the chosen event type.
What the program should do is: If exhibition is selected, the groupbox of exhibition will be visible, while having the clubbing groupbox hidden.(Vice versa if clubbing is selected)
Code:
namespace Promoter.Forms
public partial class eventCreate : Form
{
public eventCreate()
{
InitializeComponent();
//import enum value to combo box
cmbEventType.DataSource = Enum.GetValues(typeof(EventType));
}
private void eventCreate_Load(object sender, EventArgs e)
{
if (cmbEventType.Text == "Exhibition")
{
grpClubbing.Visible = false;
grpExhibition.Visible = true;
//import enum values to combo box
cmbExhibitionVenue.DataSource = Enum.GetValues(typeof(ExhibitionVenue));
}
else if (cmbEventType.Text == "Clubbing")
{
grpExhibition.Visible = false;
grpClubbing.Visible = true;
//import enum values to combo box
cmbClubbingVenue.DataSource = Enum.GetValues(typeof(ClubbingVenue));
}
}
Try using the SelectedIndexChanged event.
private void cmdEventType_SelectedIndexChanged( object sender, EventArgs e ) {
ComboBox cb = (ComboBox)sender;
grpClubbing.Visible=false;
grpExibition=false;
switch ( cb.SelectedText ) {
case "Exhibition":
grpExhibition.Visible = true;
//import enum values to combo box
cmbExhibitionVenue.DataSource = Enum.GetValues(typeof(ExhibitionVenue));
break;
case "Clubbing":
grpClubbing.Visible = true;
//import enum values to combo box
cmbClubbingVenue.DataSource = Enum.GetValues(typeof(ClubbingVenue));
break;
default:
break;
}
}
Fixed it, just had a logic missing from my mind.
Instead of
private void eventCreate_Load(object sender, EventArgs e)
I had to reason out and do it at:
private void cmbEventType_SelectedIndexChanged(object sender, EventArgs e)

Setting focus to listviews in the tabcontrol of a winform

In my project, in a form there are two list views in the tabcontrol, i am unable to set the focus to both the list view items. I am using the following code. The problem is that I am able to select only one listview among the both. Please tell me what is the alternative I can do to select both the listviews in the form.
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData1();
if (listViewClients.Items.Count > 0)
{
listViewClients.Items[0].Selected = true;
listViewClients.Select();
}
if (listView1.Items.Count > 0)
{
listView1.Items[0].Selected = true;
listView1.Select();
}
}
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData1();
switch (this.tabControl1.SelectedTab.Name)
{
case "tpUpdate":
listViewClients.Items[0].Selected = true;
listViewClients.Select();
break;
case "tpDelete":
listView1.Items[0].Selected = true;
listView1.Select();
break;
}
}

Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox

related to this topic:
Hidden ListBox will appear while Typing Words in RichTextBox
im working on a code editor and i just want to know if how can I add items from listbox to textbox using enterkey .
further more heres my strings:
public String[] ab = { "abstract" };
public String[] am = { "AmbientProperties", "AmbientValueAttribute" };
sample:
in richtextbox (rtb) , i type Ab, then hiddenlistbox will appear with "abstract" text on it (already do that) using this code:
if (token == "letterA" || token.StartsWith("Ab") || token.StartsWith("ab"))
{
int length = line.Length - (index - start);
string commentText = rtb.Text.Substring(index, length);
rtb.SelectionStart = index;
rtb.SelectionLength = length;
lb.Visible = true;
KeyWord keywordsHint = new KeyWord();
foreach (string str in keywordsHint.ab)
{
lb.Items.Add(str);
}
break;
}
then after that after i press enterkey i want to add the abstract from listbox to the richtextbox .
RichTextBox declared as rtb and ListBox declared as lb
what should i do? thanks .
Certain controls do not recognize some keys when they are pressed in key down event.
For eg ListBox do not recognize if key pressed is Enter Key.
Please see remarks section in following link -
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx
one of the solution for your problem can be
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx
implement PreviewKeyDown Event for your listbox for listbox to recognize your actions.
Here is sample code snippet -
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}
You cannot directly type text to a listbox, so I created a example with textBox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as TextBox).Text);
e.Handled = true;
}
}
If you meant comboBox you can easily adjust this, replace line above:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as ComboBox).Text);
e.Handled = true;
}
}
Copy selected listbox entries to rtf box:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
foreach (string s in listBox1.SelectedItems)
{
this.richTextBox1.AppendText(s + Environment.NewLine);
}
e.Handled = true;
}
}

Categories

Resources