C# getting form reference in an eventhandler - c#

My problem is not complicated but i've been looking up for quite some time now and can't seem to find the correct way to phrase it so if this is a duplicate I am sorry.
I have a Form created on a button click, within this Form is a table layout which contains a set of Controls (a label, a combo box and a button). What I want to do is to store the current index selected in the combo box when the button is pressed. However, I can't access the combo box when I'm in the button click event handling block.
This is the creation of my Form, nothing extraordinary.
Form settingsWindow = new Form();
settingsWindow.Text = "Connexion settings";
settingsWindow.MaximumSize = new System.Drawing.Size(200, 200);
TableLayoutPanel layout = new TableLayoutPanel();
layout.Dock = DockStyle.Fill;
Label label = new Label();
label.Text = "Choose an available COM port";
Button bt_OK = new Button();
bt_OK.Text = "valider";
bt_OK.Anchor = AnchorStyles.Bottom;
bt_OK.Name = "bt_OK";
bt_OK.Click += Bt_OK_Click;
ComboBox cb_portList = new ComboBox();
SerialComm serial = new SerialComm(); //Filling the combo box with a list of
List<string> portList = new List<string>(); //available COM ports
portList = serial.getAllPorts();
foreach(string portName in portList)
{
cb_portList.Items.Add(portName);
}
layout.Controls.Add(label);
layout.Controls.Add(cb_portList);
layout.Controls.Add(bt_OK);
What I'd like to be able to do is the following, imagine I made a class to store the data I want :
private void Bt_OK_Click(object sender, EventArgs e)
{
datacontainer.selectItem = cb_portList.SelectedItem;
settingsWindow.close();
}
Am I not able to do so because my Form is already created within an eventhandler ? Or is it just because they're in separate blocks. If so is there a way the new Form and its controls available from outside the block ?

Related

How to delete (remove) space between textboxes after remove some controls?

I'm new working with C# and I'm asking on here because I didn't find a solution searching in google and other questions on SO, I will explain what my example application does:
When I run it it display a form with a textbox by default, this textbox always will be shown, after type some text and press enter it will generate a new textbox and a new button (all the controls even the default textbox are inside a panel), and the new textboxes have the same functionality as the default textbox, when I click on the button generated next to its textbox it removes the button itself and the textbox but after that if I remove some random textboxes it leaves a space between these controls, how can reorganize this content to dont let space between them?
As you can see in the image, can you tell me how can fix this or give me an advice to achieve this? thank you, by the way this is the method I use to generate the buttons and textboxes
private void GenerarTextBox()
{
panelContenedor.VerticalScroll.Value = panelContenedor.VerticalScroll.Minimum;
TextBox tb = new TextBox();
tb.Text = "Prueba " + id;
tb.Name = "txtBox" + id;
tb.KeyDown += new KeyEventHandler(TextBox_Keydown);
Button bt = new Button();
bt.Cursor = Cursors.Hand;
bt.Text = "X";
bt.Name = "btnPrueba" + id;
bt.Click += new EventHandler(ClickBotones);
Point p = new Point(20, 30 * id);
Point pb = new Point(130, 30 * id);
tb.Location = p;
bt.Location = pb;
panelContenedor.Controls.Add(tb);
panelContenedor.Controls.Add(bt);
tb.Focus();
id++;
}
And this to remove the textboxes and the buttons
private void ClickBotones(object sender, EventArgs e)
{
Button bt = sender as Button;
string nombreBoton = bt.Name;
string idBoton = nombreBoton.Substring(9);
string nombreTextBox = "txtBox" + idBoton;
foreach (Control item in panelContenedor.Controls.OfType<Control>())
{
if (item.Name == nombreTextBox)
{
panelContenedor.Controls.Remove(item);
panelContenedor.Controls.Remove(bt);
}
}
}
You could place your dynamic controls on a FlowLayoutPanel. Either directly or grouped together in a Panel or UserControl.
Set the FlowDirection property of the FlowLayoutPanel to TopDown. The FlowLayoutPanel will then arrange your controls automatically. You can also set the WrapContents property to False and AutoScroll to true to make the scroll bar appear.
Alternatively you can use FlowDirection = LeftToRight, place the text box and the button directly on the FlowLayoutPanel and let the child controls wrap (WrapContents = True). In the child controls, a new property FlowBreak appears. It can be set to True for the last control to appear in a row and let the next one wrap independently of the width of the FlowLayoutPanel.
You can also play with the Margin property of the child controls to control their layout in the FlowLayoutPanel as the Location property becomes useless.
The FlowLayoutPanel (as well as the Panel) is available in the Toolbox in the section "Containers".
When you delete the controls, you need to do a recalc of the positions. So when you have added them in sequence, you can go with:
bool repos = false;
Point p;
foreach (Control item in panelContenedor.Controls.OfType<Control>())
{
if (repos)
{
Point tmp = item.Location;
item.Location = p;
p = tmp;
}
if (item.Name == nombreTextBox)
{
panelContenedor.Controls.Remove(item);
panelContenedor.Controls.Remove(bt);
repos = true;
p = item.Location;
}
}

C# DataGridView single button to go back

I have a form over which I have a panel. When a button is clicked, I turn my panel to invisible and I show a DataGridView ( a table from sql ). My problem is... is there any way to put a button somewhere on my form so I can go back to the main menu ( on click, to set the panel visibility to true ).
I tried using DataGridViewButtons but it's not ok. I want just one single button, anywhere on my form, called Back that would take me back. Somehow, it won't let me place a button anywhere unless I have a panel. Is there any solution?
I can add any code if necessary, just tell me which
menu.Visible = false;
DataGridView dgw = new DataGridView();
dgw.Parent = this;
dgw.Location = new Point(
this.ClientSize.Width / 3 - dgw.Size.Width / 2,
this.ClientSize.Height / 4 - dgw.Size.Height / 2);
dgw.Anchor = AnchorStyles.None;
dgw.AutoSize = true;
dgw.BackColor = Color.FromArgb(210, 121, 84);
dgw.Text = "Login";
dgw.Padding = new Padding(10);
dgw.BorderStyle = BorderStyle.FixedSingle;
While it is far more easy to create your form from the designer, placing a Button on the form code is as simple as creating the datagrid.
private void CreateButton()
{
var button = new Button
{
Text = "Press me",
Name = "SomeButtonName",
Location = new Point(10,10),
Size = new Size(100,20),
Visible = true,
};
button.Click += (s, e) => this.ButtonClicked();
this.Controls.Add(button);
}
private void ButtonClicked()
{
// this will fire on click
}
You can call `this.CreateButton()' everywhere you'll like.

Programmatically added controls not showing when added to a tab page

Up till now I have been just displaying my programmatically created controls to this.controls but now I want to add in tabbing functionality for large sets of data. I added in a tab control and in the code I have the programmatic controls added to the tabpage but I cannot get the controls to display... help what do I need to do get the controls to display
right now what i have is
private void Form1_Load(object sender, EventArgs e)
{
panel = new Panel();
panel.Location = position;
panel.BorderStyle = BorderStyle.Fixed3D;
panel.Width = 240;
panel.Height = 210;
company = new Label();
company.Location = new Point(panel.Location.X + 10, panel.Location.Y + 10);
company.Text = tempServer.Value.companyName;
company.Font = new Font(company.Font.FontFamily, 12, FontStyle.Bold);
tabs.TabPages["1"].Controls.Add(company);
this.Controls.Add(tabs);
this.Controls.SetChildIndex(tabs, this.Controls.Count);
}
Edit(to help clarify)
I have an application which reads from a database for each tuple in the data base my WinForm application creates a new panel which is then populated with various information with dynamically created labels. the position is then offset and the next panel is created. I was informed that i need to now have my application support tabs. each tab will only show so many panels. my problem accured when i tried to add these dynamically created panels to the tab control instead of this.control. when i did so the panels and their information was no longer being drawn and I cant figure out how to make the panels display
You didn't set Text for your label so you didn't see any thing, try this:
company = new Label(){Text = "some text here"};
The whole code:
private void Form1_Load(object sender, EventArgs e) {
company = new Label{Text = "some text here"};
tabs.TabPages["1"].Controls.Add(company);
this.Controls.Add(tabs);
}

How to add a control to a added tab C#

I am creating a simple application that keeps track of coins. I have a button that creates a new tab in a tabcontrol container. I am wanting to add some textboxes to the newly added tabs. The below code adds a textbox to my main tab called "Control". I have tried playing around with that field, but it always adds it to the main page called control. How would I do this? I have the following code:
string name = txtName.Text;
//validate information
try { }
catch { }
//create new tab
string title = name;
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
//Add text boxes
TextBox tb = new TextBox();
tb.Location = new System.Drawing.Point(250, 75);
tb.Name = "TextBoxName";
tb.Size = new System.Drawing.Size(184, 20);
Control.Controls.Add(tb);
//put data inside of textboxes
tb.Text = txtCoin.Text;
myTabPage.Controls.Add(tb);
You need to add the text box to the controls collection of the new tab:
//Control.Controls.Add(tb); //Replace this line
myTabPage.Controls.Add(tb);
change
Control.Controls.Add(tb)
to
tabControl1.TabPages.Last().Controls.Add(tb)
tabControl1.TabPages.OfType<TabPage>().Last().Controls.Add(tb)

Adding and removing dynamic controls Windows Forms using C#

I have three Tabs in my Windows Forms form. Depending on the selected RadioButton in the TabPages[0], I added few dynamic controls on the relevant TabPage. On the Button_Click event the controls are added, but the problem is I'm not able to remove the dynamically added controls from the other (irrelevant) TabPage.
Here's my code:
Label label235 = new Label();
TextBox tbMax = new TextBox();
label235.Name = "label235";
tbMax.Name = "txtBoxNoiseMax";
label235.Text = "Noise";
tbMax.ReadOnly = true;
label235.ForeColor = System.Drawing.Color.Blue;
tbMax.BackColor = System.Drawing.Color.White;
label235.Size = new Size(74, 13);
tbMax.Size = new Size(85, 20);
if (radioButton1.Checked)
{
label235.Location = new Point(8, 476);
tbMax.Location = new Point(138, 473);
tabControl.TabPages[1].Controls.Add(label235);
tabControl.TabPages[1].Controls.Add(tbMax);
tabControl.TabPages[2].Controls.RemoveByKey("label235");
tabControl.TabPages[2].Controls.RemoveByKey("tbMax");
}
else
{
label235.Location = new Point(8, 538);
tbMax.Location = new Point(138, 535);
tabControl.TabPages[1].Controls.RemoveByKey("label235");
tabControl.TabPages[1].Controls.RemoveByKey("tbMax");
tabControl.TabPages[2].Controls.Add(label235);
tabControl.TabPages[2].Controls.Add(tbMax);
}
Where am I making that mistake?
First of all, tbMax's name is not "tbMax", but "txtBoxNoiseMax". So for one, it won't be able to find the TextBox on RemoveByKey.
You're making new controls each time.
As lc already mentioned:
You named your TextBox variable tbMax, but you gave it the name txtBoxNoiseMax. If you take a look into the description of RemoveByKey, you'll see it works on the Name property. So you should change
tbMax.Name = "txtBoxNoiseMax";
into
tbMax.Name = "tbMax";

Categories

Resources