How to access data from one form and bring to another - c#

I am trying to pull a label text into another form inside the same solution to use in an if statement. However, it seems as though it's not pulling the data from the field. I am trying to change the color of the label background based on the label text in form 1. Any help is greatly appreciated.
IN FORM 1:
public void button1_Click(object sender, EventArgs e)
{
form1 view = new form();
view.Show();
view.label1 = label1.Text.ToString();
}
IN FORM 2:
public string label1 { get; set; }
public void Display()
{
if (label1 == "1")
{
for (int i = 0; i < nWinnings.Length; i++)
{
Label label = new Label();
label.BackColor = Color.Red;
...
}
}
else
{
for (int i = 0; i < nWinnings.Length; i++)
{
Label label = new Label();
label.BackColor = Color.Blue;
...
}
}
}
There is more to the label but the label is working fine minus the color change.

This is incorrect:
Label label = new Label();
You cannot create a new instance of your Label... it has absolutely no connection to the original Label instance in the first Form, and changing any property on it will not affect the original one either.
You'll need to pass a reference to the entire Label:
// Form 1
public void button1_Click(object sender, EventArgs e)
{
form1 view = new form();
view.label1 = label1;
view.Show();
}
// Form 2
public Label label1 { get; set; }
public void Display()
{
if (label1.Text == "1")
{
for (int i = 0; i < nWinnings.Length; i++)
{
label1.BackColor = Color.Red;
// ... etc, etc
I'd limit how much passing around of references to controls you do to other Forms. In my experience, code starts to get quite muddy when you do that too much.

If what I understood is correct, you have 2 forms. FORM1 & FORM2.
You have a label control LABEL1 in FORM1. You read this text and pass it to FORM2.
In FORM2, you have another label control LABEL2, whose background color you want to change.
You can declare a string variable in FORM2.
Add a new constructor to FORM2 to accept a string argument, and set this value to the string variable.
In FORM2 OnLoad, you can then check the value of your string variable and
then,
LABEL2.BackColor = whateverColor in the if-else loop.
something like this in FORM1
FORM2 newForm = new FORM2(LABEL1.Text);
newForm.Show();
and in FORM2
private label1String = String.Empty();
public FORM2(string arg)
{
...Default Initialization Code...
label1String = arg;
}
private void ChangeLabel2Color()
{
if(label1String == "1")
{
LABEL2.BackColor = whateverColorYouNeed;
}
else
{
...WHATEVER YOU NEED TO DO...
}
}
I wrote the code directly, so there might be syntax errors.

Related

How to display Form Components from List

this question might be really stupid but here it is anyway. What I want my programm to do: When I press a button I want to add a DatePicker Component to a List and then display all the Components in the Main Form. However when I press the button it only adds the components but doesnt show them in the Form Window. No Errors are thrown. What do I have to do to display the DatePicker Components in the Main Form?
//class containing the List of Components
class Eintrag
{
static public List<DateTimePicker> Anfangszeit = new List<DateTimePicker>();
}
//Main Form Class
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Eintrag.Anfangszeit.Add(new DateTimePicker());
for (int i = 0; i < Eintrag.Anfangszeit.Count; i++)
{
Eintrag.Anfangszeit[i].Location = new System.Drawing.Point(30, 50 + 50*i);
Eintrag.Anfangszeit[i].Size = new System.Drawing.Size(200, 20);
Eintrag.Anfangszeit[i].Visible = true;
Eintrag.Anfangszeit[i].Show();
}
}
}
John Wu is right, you have to add the Controls to the Form via Controls.Add()
private void button1_Click(object sender, EventArgs e)
{
Eintrag.Anfangszeit.Add(new DateTimePicker());
for (int i = 0; i < Eintrag.Anfangszeit.Count; i++) {
Eintrag.Anfangszeit[i].Location = new System.Drawing.Point(30, 50 + 50 * i);
Eintrag.Anfangszeit[i].Size = new System.Drawing.Size(200, 20);
Eintrag.Anfangszeit[i].Visible = true;
this.Controls.Add(Eintrag.Anfangszeit[i]);
Eintrag.Anfangszeit[i].Show();
}
}

C# how to make function for all buttons using object sender

I´m using WindowsForm and working with flat design. In the program there are 6 buttons, these buttons are made of a label and a panel. The label controls all the actions that the button can do. when i started writing the program i made one function for each button, now i like to use one function that controls all buttons. I have tried to make that work but I´m stuck and can´t find a way to solve it.
Been looking around at the forum for solutions but i think that i might not know what i´m looking for.
This is what i made so far.
Buttons[] cobra = new Buttons[5];
private class Buttons
{
private bool position;
private string name;
public bool Position
{
get { return position; }
set { position = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
private void SetButtons()
{
cobra[0].Name = "label3";
cobra[0].Position = false;
cobra[1].Name = "label4";
cobra[1].Position = false;
}
private void CheckStatusButtons(object import)
{
for (int i = 0; i < cobra.Length; i++)
{
}
}
private class ToggelFunction
{
private bool hawk;
public bool Hawk
{
get { return hawk; }
set { hawk = value; }
}
}
ToggelFunction tiger = new ToggelFunction();
private void label3_Click(object sender, EventArgs e)
{
if (tiger.Hawk == false)
{
button1.BackColor = Color.PaleGreen;
label3.Text = "ON";
if (myport.IsOpen)
{
send(new byte[] { 16, 128, 32, 16, 1 });
}
tiger.Hawk = true;
return;
}
if (tiger.Hawk == true)
{
button1.BackColor = Color.DarkSeaGreen;
label3.Text = "2";
if (myport.IsOpen)
{
send(new byte[] { 16, 128, 32, 8, 1 });
}
tiger.Hawk = false;
return;
}
}
"label3_Click" this is my function for button 1, all buttons look the same just different variables.
As I found on the forum, you can use object sender to i identify which button that made the click and from there use that in the function to make action.
So all buttons will use this functions, i´m not sure how to compare values in the if statement, if button 1 is click then it should check what values button 1 has.
My idea was to make a class "Buttons" and an array to store all the values of each button, it´s not completed yet. When a button is clicked it checks
with the array what values that button has and compare that in the function depending on what the action is. The first action would be to check if the button is on or off. If it´s off then it enters that if statement and there some actions will happen, change of color and the text, these values also have to be stored in the array i guess.
I have tried to compare the array with object sender, but i get some error saying that you can´t compare bool with object i think.
So i wonder if some one might have a solution or suggestions?
I have made a simple example of what i think you want to do. bare in mind this does not abide by all coding best practises but its not a mess either. You will need to put your safety null checks in.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class ButtonVariables
{
public int value1 { get; set; }
public int value2 { get; set; }
}
Dictionary<string, ButtonVariables> bv = new Dictionary<string, ButtonVariables>();
private void ProcessClick(object sender, EventArgs e)
{
ButtonVariables vars = GetVariables(sender);
//Do stuff with your variable set here
}
private ButtonVariables GetVariables(object sender)
{
ButtonVariables returnValue = new ButtonVariables();
switch (((Button)sender).Name.ToLower())
{
case "buttona":
return bv["A"];
case "buttonb":
return bv["B"];
case "buttonc":
return bv["C"];
default:
break;
}
return null;
}
private void ButtonA_Click(object sender, EventArgs e)
{
ProcessClick(sender, e);
}
private void ButtonB_Click(object sender, EventArgs e)
{
ProcessClick(sender, e);
}
private void ButtonC_Click(object sender, EventArgs e)
{
ProcessClick(sender, e);
}
}
I've basically added two methods to handle your method. One to identify the button and get its related values from a dictionary that you will have to populate with your Buttons class. and one to carry out the logic.
EDIT
As requested in the comments here's an easy (but not the only way) to point your event listeners towards the same method.
Initially you need to set up with one button and double click it or do some other way to create the forms Button_Click() Event Method. At this point an event listener delegate has been added to your Form.Designer.cs File. Open that file and you will see something like this:
//
// ButtonA
//
this.ButtonA.Location = new System.Drawing.Point(12, 12);
this.ButtonA.Name = "ButtonA";
this.ButtonA.Size = new System.Drawing.Size(75, 23);
this.ButtonA.TabIndex = 0;
this.ButtonA.Text = "button1";
this.ButtonA.UseVisualStyleBackColor = true;
this.ButtonA.Click += new System.EventHandler(this.ButtonA_Click);
What you need to do is create your other buttons and add this code in for them with a change to the last line new System.EventHandler(this.ButtonA_Click); This line basically states which method to call when the ButtonA.Click event is invoked. At this point you can add what ever method you want (as long as you name is nicely for good convention). So your example would be this :
//
// ButtonA
//
this.ButtonA.Location = new System.Drawing.Point(12, 12);
this.ButtonA.Name = "ButtonA";
this.ButtonA.Size = new System.Drawing.Size(75, 23);
this.ButtonA.TabIndex = 0;
this.ButtonA.Text = "button1";
this.ButtonA.UseVisualStyleBackColor = true;
this.ButtonA.Click += new System.EventHandler(this.ProcessClick);
//
// ButtonB
//
this.ButtonB.Location = new System.Drawing.Point(12, 12);
this.ButtonB.Name = "ButtonB";
this.ButtonB.Size = new System.Drawing.Size(75, 23);
this.ButtonB.TabIndex = 0;
this.ButtonB.Text = "B";
this.ButtonB.UseVisualStyleBackColor = true;
this.ButtonB.Click += new System.EventHandler(this.ProcessClick);
//
// ButtonC
//
this.ButtonC.Location = new System.Drawing.Point(12, 12);
this.ButtonC.Name = "ButtonC";
this.ButtonC.Size = new System.Drawing.Size(75, 23);
this.ButtonC.TabIndex = 0;
this.ButtonC.Text = "C";
this.ButtonC.UseVisualStyleBackColor = true;
this.ButtonC.Click += new System.EventHandler(this.ProcessClick);
Remember you need to physically create the buttons on the form itself.
Lets say you have three labels and a panel for each label. You can add the event handler to all of them and whenever that event fires the event handler will use that label as the sender. To keep the panel associated with the label, you could add the panel to the label's tag property. Then, in the event handler you can then get the panel from the label.
label1.Click += label_Click;
label2.Click += label_Click;
label3.Click += label_Click;
label1.Tag = panel1;
label2.Tag = panel2;
label3.Tag = panel3;
In the event handler, just cast sender to Label and there you have your label object to do whatever you want with and like I said, the panel is in the Tag property. I did a little refactoring to your code to make it cleaner looking.
private void label_Click(object sender, EventArgs e)
{
// this is what itsme86 was suggesting in the comments
var label = (Label)sender;
var panel = (Panel)label.Tag;
label.BackColor = tiger.Hawk ? Color.DarkSeaGreen : Color.PaleGreen;
label.Text = tiger.Hawk ? "2" : "ON";
if (myport.IsOpen)
send(new byte[] { 16, 128, 32, 8, 1 });
tiger.Hawk = !tiger.Hawk;
}
Let me know if you have any questions about this.

Using Dynamic Textboxes in C# Program

I am trying to make number of TextBoxes according to number in TextBox1 and I want to use each TextBox value in my program. Their name becames txtbx0, txtbx1... but when I want to use in my program, it gives error "The name 'txtbx1' does not exist in the current context". How can I use them in my program?
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
TextBox[] txtbx = new TextBox[y];
for (int i = 0; i < y; i++)
{
txtbx[i]= new TextBox();
txtbx[i].Location = new Point(20, i * 50);
txtbx[i].Size = new Size(100,50);
txtbx[i].Name = "txtbx"+i.ToString();
txtbx[i].Text = txtbx[i].Name;
flowLayoutPanel1.Controls.Add(txtbx[i]);
}
}
The way you have it right now, the textboxes could be accessed by using your array txtbx[whateverNumber]. In order to make them accessible outside of the method you posted, you'll need to make your txtbx array a class member instead of a method-scoped variable.
Something like:
class Form1 : Form
{
TextBox[] txtbx;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int y = Convert.ToInt32(textBox1.Text);
txtbx = new TextBox[y]; // Now this references the class member
for (int i = 0; i < y; i++)
... etc.
}
}
Accessing them individually by name is not really feasible because you'd have to have class member variables for each of them, but you don't know up front how many to make. The array method like you're doing is much better. You can just access them in other methods using txtbx[0] through txtbx[numBoxes - 1].

Use Form Constructor repeatedly to refresh the label text

I'm newbie for C# and i have a little project. I'm stucked somewhere. I explained it here (with sample source codes) :
I have a form application. I'm asking users select an option from 2 buttons. There are 2 buttons (YES and NO) . My codes like this :
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
}
}
As you see, when user click one of YES or NO button, whole constructor function should be re-executed. And label should be "You just pushed YES / NO button".
But when i use this.Refresh() , nothing happening when i clik buttons. Still label is "Please push one of these buttons :" .
When i use this.Invalidate() , all buttons disappering, and label is still "Please push one of these buttons :" .
What should i do ?
Thanks.
PS
I've found this question BEFORE ask this one. But as you see, accepted answer not working for me.
Invalidating or refreshing doesn't call the constructor again. The constructor is called exactly once when the form is created, and invalidating doesn't create a new form. Put the logic for changing stuff in another method and call that from the constructor AND from the event handlers - but do note for posterity that calling instance methods or accessing variables from the constructor isn't really the nicest way of doing this stuff - but for your purposes here it's the simple solution.
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
UpdateForm();
}
private void UpdateForm(){
if(choice == 0)
{
label.Text = "Please push one of these buttons :";
// And there are buttons below this label
}
else if(choice == 1)
{
label.Text = "You just pushed YES button";
}
else if(choice == 2)
{
label.Text = "You just pushed NO button";
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
choice = 1;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
private void buttonNo_Click(object sender, EventArgs e)
{
choice = 2;
/*
I have to use one of these here for redraw whole form
this.Refresh();
this.Invalidate();
*/
UpdateForm();
}
}
This is how you really should be doing it:
public partial class Form1 : Form
{
public Form1()
{
// Isn't there supposed to be InitializeComponent() here?
// You should assign this in the designer, rather than here.
label.Text = "Please push one of these buttons :";
}
private void buttonYes_Click(object sender, EventArgs e)
{
label.Text = "You just pushed YES button";
}
private void buttonNo_Click(object sender, EventArgs e)
{
label.Text = "You just pushed NO button";
}
}
Since all the button is doing is changing a label, that should be done directly, not though changing a variable and refreshing.
But why didn't it work my way?
All Refresh and Invalidate do is redraw what is already on your form. They don't recreate it.
A constructor is designed to initialize an object once, when you create it. It cannot be called to 'reinitialize' or 'refresh' an object.
To avoid going into too much detail, I recommend you find an article/book on object oriented programming to learn more about constructors and other OOP idioms.
This is the best option if you want to keep the same variables as in the exemple. If you want a shorter version just change the label directly in the Form1 Constructor.
public partial class Form1 : Form
{
public int choice=0;
public Form1()
{
buttonYes.Click += (s,e) => {
choice = 1;
ChangeText(choice);};
buttonNo.Click += (s,e) => {
choice = 2;
ChangeText(choice);};
}
private void ChangeText(int userChoice)
{
if(choice == 0)
label.Text = "Please push one of these buttons :";
else if(choice == 1)
label.Text = "You just pushed YES button";
else if(choice == 2)
label.Text = "You just pushed NO button";
}
}
Shorter Version
public partial class Form1 : Form
{
public Form1()
{
label.Text = "Push a button";
buttonYes.Click += (s,e) => {label.Text = "Yes is pressed";};
buttonNo.Click += (s,e) => {label.Text = "No is pressed";};
}
}
Main Constructor execute when new object created .
use an Method for do this . and i am shore this will work
public string TextSwitcher(int choice)
{
Switch(choice) // choice is an int
{
// 1,2,3 is not an serial no they will pass by parameter
case(1):
return "Please push one of these buttons :";
brake;
case(2):
return = "You just pushed YES button";
brake;
case(3)
return = "You just pushed NO button";
brake;
}
}
private void buttonYes_Click(object sender, EventArgs e)
{
label.Text = TextSwitcher(2);
}
private void buttonNo_Click(object sender, EventArgs e)
{
label.Text = TextSwitcher(3);
}
i hop this will help you . and welcome for you'r thank's .
best of luck

I want to get the particular column value of the current row of the datagrid view into text box of another form. How can I do it. I am using c sharp

I want to pass the column value of the current row of the datagridview. I have a button on one column in the datagridview. When I click on the button , another form opens up. I have a text box on the another form. So I want to get the column value of the current row on the text box of another form. I am using c sharp.
Any help is appreciated.
Here is an example using the constructor to receive the value:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//test data
this.dataGridView1.Rows.Add(1);
this.dataGridView1[1, 0].Value = "testValue1";
this.dataGridView1[1, 1].Value = "testValue2";
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//Button is in column 0.
if ((e.ColumnIndex != 0) || (e.RowIndex < 0)) { return; }
string valueToPass = (dataGridView1[1, e.RowIndex].Value as string) ?? String.Empty;
Form2 f2 = new Form2(valueToPass);
f2.Show();
}
}
public partial class Form2 : Form
{
public Form2(string valueFromOtherForm)
{
InitializeComponent();
this.textBox1.Text = valueFromOtherForm;
}
}

Categories

Resources