This question already has answers here:
Bind a label to a "variable"
(4 answers)
Closed 3 years ago.
I want to pass my Label I use in my mainForm to an anonymous form. By anonymous form I mean this form count can be infinite. I will show my code to make it clear.
This is my second form.
LABEL sourceObj;
public frmCounters(string text, ref LABEL _sourceObj)
{
InitializeComponent();
sourceObj = _sourceObj;
this.Text = text;
this.lblInfo.Text = text;
this.lblTime = sourceObj;
}
and this is how I call it
AnonymForm afrm = new AnonymForm("TEST1", ref lblTEST1);
afrm.Show();
all I want to achieve here is update anonyform's label whenever I change the source from my main form. I have tried with and without ref keyword in constructor. I've bind the value I get in constructor to another variable I hold in anonymform. I also wanted to try send text property as reference but Visual Studio said I can't pass properties with ref keyword.
My question is how can I achieve that?
Add to AnonymForm class method like:
public void SetLabelText(string value)
{
this.label.Text = value;
}
And call it from main form:
afrm.SetLabelText("TEXT");
Related
I'm creating Library app using WinForms.
I have eLibraryClasses where I have all data including each form services, and eLibraryUI where I have all my WinForms.
I have a problem in one form where I would like to change states of button.Visible to false or true.
I tried to extract method from UI to Service like:
public void ShowDrawnBook(bool clickedButtonVisible, bool toReadButtonVisible, int buttonNumber)
{
//Hide button which cover answer
clickedButtonVisible = false;
//Add option to add randomized book to "To read" bookshelf
toReadButtonVisible = true;
//Return index of clicked button
buttonClicked = buttonNumber;
}
And UI looks like for example:
service.ShowDrawnBook(randomBook2Button.Visible, toReadButton.Visible, 2);
I tried, but I couldn't use "ref" neither "out" for this properties.
And in this way above it's building properly, but not working because of not changing parameters out of method.
I have such a many of them in this form, so I could do it like
randomBook2Button.Visible = SomeMethod();
toReadButton.Visible = SomeMethod();
... for every variable
But I would like to avoid it.
Is there any way to send there buttons properties (bools) as parameters?
Booleans are passed by value, not reference, thus your "problem".
To solve your problem, just take the Button(s) as parameters instead of the booleans. Button is a class, thus is passed by reference.
Then in your method change the state of the Button(s) properties as you see fit.
public void MyMethod(Button myButton1, Button myButton2)
{
myButton1.Visible = true;
myButton2.Visible = false;
}
This question already has answers here:
Find control by name from Windows Forms controls
(3 answers)
Closed 4 years ago.
Using C# and Windows Forms, i would like to use the name of a Label as a parameter of another function, like this:
startBox(label_box, "11", Color.Red);
Definition of startBox:
private void startBox(Label label, string text, Color color) {
label.BackColor = color;
label.Visible = true;
label.Enabled = true;
label.Text = text;
}
But, is there any way to convert an string to the name of a Label?
In my case, label_box is a string.
ps¹. I need to do this because i have N Labels and the name is should be typed by the user.
ps². To Invoke a method using a string i used the MethodInfo.
EDIT: The solution using Controls does not apply. In my case, a string is given as an input, if the string is the name of one of the labels the function is called.
Thank you, and sorry for the spelling flaws in English.
so you want to be able to operate on a label, where the name of the label is supplied as input. I would do this with a dictions
var lDict = new Dictionary<string, Label>();
lDict["l1"] = Label1;
lDict["l2"] = Label2;
....
then
void Func(string labelName)
{
var label = lDict[labelName];
label.Visible = true;
...
}
you could do all sorts of complicated reflection tings but that feels like overkill
I have one main form with controls like datagridview, combobox , textboxes and so on.I have created another which i want to use it as a wizard for selection as am trying to make it look user friendly. Now i want to be able to inherit controls inside the main form. i don't have a class nor create it as i don't wanna use it. i know how to create class and call my class within the form i want to access the method, properties and function.
How can i access the controls from one form to another.
e.g datagridview and textbox are from form1. on form two,i want to be able to access those two controls(datagridview and textbox). Please note here am giving as an example but from my main form i have more that two kinds of control.
My code from the wizard form
private void btnBrosweInput_Click(object sender, EventArgs e)
{
BrowseFile();
ReadFile(ref Gridview_Input,
ref txtInputfile,
ref cboLanguage,
bref btnNewfile);
//Errors that m getting from this method
1.Gridview_Input' does not exist in the current context
2.The best overloaded method match for .FrmExisitngFile.ReadFile(ref System.Windows.Forms.DataGridView, ref System.Windows.Forms.TextBox, ref System.Windows.Forms.ComboBox, ref System.Windows.Forms.Button)' has some invalid arguments
3.Error 5 Argument 1: cannot convert from 'ref Gridview_Input' to 'ref System.Windows.Forms.DataGridView'
}
I have place this method for readfile on the form
private void ReadFile(ref DataGridView _Grid, ref TextBox _InputTexBox, ref ComboBox _cboLanguage, ref Button _btnNew)
{
_Grid.Rows.Clear();
string PathSelection = "";
if (_InputTexBox.Text.Length > 0)
{
PathSelection = _InputTexBox.Text;
}
oDataSet = new DataSet();
XmlReadMode omode = oDataSet.ReadXml(PathSelection);
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[] { oDataSet.Tables["data"].Rows[i][0].ToString(), oDataSet.Tables["data"].Rows[i][1].ToString(), font, datestamp, commentVal };
_Grid.Rows.Add(row);
_btnNew.Enabled = true;
}
}
from the wizard form am trying to access the controls from the main form which contains the grid where everything will get loaded on
There is a lot of things going on in your code, but the main problem is that you try to manipulate data from your UI controls. This is a tremendously bad idea and it dramatically complicates your design (as you can already see from this fairly small feature).
As I stated in the OP's comments, you don't want to manipulate the controls to work with data. You want to manipulate data from POCO (Plain Old CLR Objects). And then update (or better: databind) all the controls that expose those data.
So you should start by doing something like this:
public class Form2 : Form
{
private List<Things> _listOfThings;
private string _inputText;
private LanguageEnum _lang;
...
// Receives data, NOT controls!
public Form2(List<Things> listOfThings, string inputText, LanguageEnum lang, ...)
{
_listOfThings = listOfThings;
...
}
...
}
Your Form1 reflects the state of listOfThings via a DataGridView, inputText via a TextBox and so on. You get the idea. Form1 pass those data (NOT the controls) to Form2 via constructor injection:
Form2 form2 = new Form2(listOfThings, inputTextBox.Text, ...);
form2.ShowDialog();
You read and update the data using the private fields in the Form2 class. When Form2 is closed, you update Form1's controls, either explicitly or using Databinding.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
(c# + windows forms) Adding items to listBox in different class
I want to get the combobox value in form1 and use it at form2, because the value will return another data from the registered user
public void povoacboxcliente()
{
List<SM.BancoDados.BD.Model.Clientes> lstClientes = new List<SM.BancoDados.BD.Model.Clientes>();
ClienteFlow flow = new ClienteFlow();
lstClientes = flow.RetornaClientes();
cboxCliente.DataSource = lstClientes;
cboxCliente.DisplayMember = "Nome";
cboxCliente.ValueMember = "Id";
}
Now the value member (Id) will return the sex of the member, that is on database, this part is ok, but what I want is to do the operation in another form.. Here is the code that I'm trying on form2
public void enviasexo()
{
EnviarComando("0238373b3be503");
idClient = Convert.ToInt32(cboxCliente.SelectedValue);
UsuarioFlow usuarioFlow = new UsuarioFlow();
string combo = cboxCliente.SelectedValue.ToString();
string sexo = usuarioFlow.RetornaSexo(combo);
if (sexo == "M")
{
Thread.Sleep(2000);
EnviarComando("0232343b3bdc03");
Thread.Sleep(200); //envia comando
}
else if (sexo == "F")
{
Thread.Sleep(2000);
EnviarComando("0232353b3bdd03");
Thread.Sleep(200);
}
}
the "cboxCliente" was used in form1
Thanks People!
One way is to make the ComboBox public in Form1.Designer.cs
then access the ComboBox from Form2
Form Form1Object = new Form1();
Form1Object.cboxCliente.SelectedValue.ToString();
See similar answer at
Stack Overflow Answer for other similar question
Please use one of State management techniques which are available in Asp.Net when passing values in different forms.
see this
http://www.codeproject.com/Articles/331962/A-Beginner-s-Tutorial-on-ASP-NET-State-Management
Client side state management techniques
View State
Control State
Hidden fields
Cookies
Query Strings
Server side state management techniques
Application State
Session State
As a best practise form 2 should not be shown to user if one of the control value is strictly dependant on form 1...input from the user. apply page validation on form 2 and
redirect user to form1 if the values from the drop down is not selected..
hope this helps
[shaz]
I have a winforms application.
I have a textbox on one form (call F1) and when a button is clicked on this form (call F2), it launches another form.
On F2, I want to set a string via a textbox (and save it to a variable in the class), and then when I close this form, the string will appear in a label in F1.
So I am basically sharing variables between both forms. However, I can't get this to work correctly. How would this code look?
I would add a new property to form2. Say it's for a phone number. Then I'd add a friend property m_phone() as string to form 2. After showing an instance of form2 but before closing it, you can refer to the property m_phone in form1's code.
It's an additional level of indirection from Matthew Abbott's solution. It doesn't expose form2 UI controls to form1.
EDIT
e.g.:
public string StoredText
{
get;
private set;
}
inside the set you can refer to your UI control, like return textBox1.text. Use the get to set the textbox value from an earlier load.
And:
public string GetSomeValue()
{
var form = new F2();
form.ShowDialog();
return form.StoredText;
}
Just ensure that StoredText is populated (or not, if appropriate) before the form is closed.
Are you showing the second form as a dialog, this is probably the best way to do it. If you can avoid doing shared variables, you could do the following:
public string GetSomeValue()
{
var form = new F2();
form.ShowDialog();
return form.TextBox1.Text;
}
And called in code:
Label1.Text = GetSomeValue();
This might not be the most efficient way of approaching, but you could create a class called DB (database). Inside this class, create variables like
public static bool test or public static bool[] test = new bool[5];
In your other forms, you can just create an instance. DB db = new DB(); then grab the information using db.test = true/false. This is what I've been doing and it works great.
Sorry, I'm only like a year late.