I'm trying to call a method from a different form on buttonclick.
If I debug it it does go to the method that I'm trying to call, but as soon as I try to change a textbox inside this function it doesn't work.
Here is my function
public void addedtram(string tramno, string rail, string lineno, string sect)
{
String tbx = "tbx_sect" + 1 +"L"+ 2;
TextBox tb = (TextBox)this.FindControl(tbx) as TextBox;
if (tb != null)
{
tb.Text = tramno;
tbx_sect10L1.Text = tramno;
}
}
I just put this in as a test, because I'm sure that the tbx exists but and with the debug it does say tb.Text = "1234"(example) but it doesn't show on my form.
Does anyone have a clue what the problem could be here?
If I understand you correctly, you should expose the contents of the textbox using a property:
class Form1 {
public string txtbox {
get { return textBox1.Text; }
}
}
Then in Form2 do this:
var frm = new Form1();
textBox1.Text = frm1.txtbox;
You can make frm a class var of Form2 and call .Show() in the constructor of Form2.
Related
What i am trying to do here is get the value from a Textbox on another form back to the main form.
In FormMain i have this function:
private void FillList(string type, HtmlNode form)
{
try {
var nodes = form.SelectNodes("//form" + type);
if (nodes != null)
{
foreach (HtmlNode elem in nodes)
{
var eleTY = elem.Attributes["type"] == null ? elem.Name.ToString() : elem.Attributes["type"].Value;
var eleNM = elem.Attributes["id"] == null ?
elem.Attributes["name"] == null ? "" : "name"
: "id";
var eleVU = elem.Attributes["id"] == null ?
elem.Attributes["name"] == null ? "" : elem.Attributes["name"].Value
: elem.Attributes["id"].Value;
var elePR = Helpers.PredictValue(eleVU);
var eleSL = "";
// check for select ...
if (eleTY == "select") {
FormInput fi = new FormInput(this, eleTY, eleVU);
fi.Show();
}
// first checked id then name ...
listViewMain.Items.Add(new ListViewItem(new string[] {
elem.Attributes["type"]==null? elem.Name.ToString():elem.Attributes["type"].Value
,
elem.Attributes["id"]==null?
elem.Attributes["name"]==null? "":"name"
:"id"
,
elem.Attributes["id"]==null?
elem.Attributes["name"]==null?"": elem.Attributes["name"].Value
: elem.Attributes["id"].Value
,
eleNM + "|" + eleVU + "|" + eleSL + "|" + elePR
}));
// check the mode and append to it ...
if (comboBoxMode.Text == "mode_register") {
txtBoxUploadRegisterMacro.AppendText(eleNM + "|" + eleVU + "|" + eleSL + "|" + elePR + Environment.NewLine);
}
// check the mode and append to it ...
if (comboBoxMode.Text == "mode_login_and_post")
{
txtBoxUploadLoginAndPostMacro.AppendText(eleNM + "|" + eleVU + "|" + eleSL + "|" + elePR + Environment.NewLine);
}
}
}
} catch (Exception) {
// handle ...
}
}
Once i have a ```select``` attribute another form will popup ```FormInput``` here i will input a value and hit a button, once the button is pressed i am trying to get the value of ```txtBoxInput.Text``` back to the ```FormMain``` i will hopefully store the returned value in the ```eleSL``` variable.
My ```FormInput``` working:
public partial class FormInput : Form
{
FormMain _formMain;
public FormInput(FormMain formMain, string eleType, string eleName)
{
_formMain = formMain;
InitializeComponent();
lblTypeInput.Text = eleType;
lblNameInput.Text = eleName;
}
private void BtnInput_Click(object sender, EventArgs e)
{
// pass the value of txtBoxInput.Text back to FormMain here ...
this.Close();
}
}
I can pass the instance of FormMain to FormInput but i'm clueless on how to get it back, any help would be appreciated.
There are a couple of points to be made here. One is do you want the input form to be modal ( to wait until it is closed before proceeding)? If yes then you need to initialize the form and call .ShowDialog() when the input is needed. Otherwise you need to have the form showing with .Show() prior to calling the fill list method and just pull values from the reference to input form using properties.
Input Form
public partial class InputForm : Form
{
public InputForm()
{
InitializeComponent();
}
public string Value
{
get => textBox1.Text;
set => textBox1.Text = value;
}
}
Either way the input form needs properties that exposes your data. That being either a single value, multiple values or a custom class.
Modal Approach
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void FillList()
{
var fi = new InputForm();
fi.Value = textBox1.Text; // set initial value from main form
if (fi.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fi.Value; // get input value back to main form
}
}
}
In order for this to work you need to set the .DialogResult property of each button in the input form accordingly, and set the .AcceptButton and .CancelButton properties of the input form. This will take care of closing the form when done, and setting the DialogResult return to .ShowDialog() in order to know if the user pressed [OK] or [Cancel].
Non-Modal Approach
public partial class MainForm : Form
{
InputForm fi = new InputForm() { Value = "Default" };
public MainForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
fi.Show(this);
}
private void FillList()
{
textBox1.Text = fi.Value; // grab whatever value the input form has
}
}
In this approach, the input form isn't blocking the flow of the main form, but you don't know when a user has changed the value. When the method runs, it just pulls whatever value happens to be in the input form text box (and hence the .Value property).
I prefer to do this by adding a public property to your second form. This property getting can either return the string from the text box, or a variable if it has been set.
This is the more object-oriented approach as the second form controls what is returned.
I wrote a code that is build from 2 forms,
the main form - (Form1) that gets 3 strings from the sub form (AddTask)
In the main form:
public partial class Form1 : Form
{
int count = 0;
string taskName2, DateTime2, More2;
public Form1(string taskName1, string DateTime1, string More1, bool startworking)
{
InitializeComponent();
taskName2 = taskName1;
DateTime2 = DateTime1;
More2 = More1;
if(startworking)
{
StartWorking();
}
}
You can see I create 3 string to global use, Form1 gets 3 strings and 1 boolean variable. When the boolean is true the function StartWorking start.
In the sub form I have a button and 3 text boxes. The button has a click event:
string taskName1 = textBox1.Text;
string DateTime1 = textBox2.Text;
string More1 = textBox3.Text;
Form celender = new Form1(taskName1, DateTime1, More1, true);
this.Close();
So when I press the button on the sub form the boolean is set to true and the StartWorking function starts.
Up to here all is alright.
The function StartWorking:
public void StartWorking()
{
MessageBox.Show(taskName2 + " " + DateTime2 + " " + More2);
ListViewItem lvi = new ListViewItem(taskName2);
lvi.SubItems.Add(DateTime2);
lvi.SubItems.Add(More2);
listView1.Items.Add(lvi);
}
Now in the function the MessageBox works and shows the strings, but when I see the listview1 nothing changes. Why doesn't it create anything?
You didn't show Form1 after instantiating it. Show the Form1 with Show() method celender.Show(); and also change your code like this:
Hide();
string taskName1 = textBox1.Text;
string DateTime1 = textBox2.Text;
string More1 = textBox3.Text;
Form1 celender = new Form1(taskName1,DateTime1,More1,true);
celender.Show();
celender.Closed += (s, args) => this.Close();
I am using Form2 to update the default printer and send the string to Form3. I typically have no problem operating from Form1 and passing data to Form2 or Form3. But having trouble using Form2 to update Form3!
The real names are: Form1 = Form1, Form2 = formUserSettings, Form3 = formViewDwg
Here is the code in Form1, calling Form2 (formUserSettings):
private void configureStartupSettingsToolStripMenuItem_Click(object sender, EventArgs e)
{
formUserSettings frmUsr = new formUserSettings(prnNameString, prnDriverString, prnPortString,
Settings.Default.DefaultPrinter.ToString(), Settings.Default.ViewStyle, Settings.Default.ReCenterEVafterDwgClose,
Settings.Default.SyncListDwgNum, listMain);
frmUsr.ValueUpdated += new ValueUpdatedEventHandler(frmUsr_ValueUpdated); //---added 3-22-12
//frmUsr.ValueUpdated2 += new ValueUpdatedEventHandler(newPrn_ValueUpdated); //---added 4-12-12
frmUsr.ShowDialog();
frmUsr.Close();
}
Here's the code inside Form2 (formUserSettings) that tries to send the printer name to Form3 (formViewDwg).
if (Application.OpenForms.OfType<formViewDwg>().Count() > 0)
{
newEntry = comboPrinters.Items[index].ToString();
formViewDwg frmVd = this.Owner as formViewDwg;
delPassData del = new delPassData(frmVD.passedNewVal);
del(newEntry);
}
else
{
frmVD = new formViewDwg(EViewMethods.currentPartPath, EViewMethods.currentPartNum, EViewMethods.currentDwgNum,
Settings.Default.DefaultPrinter, Settings.Default.DefaultPrinterDriver, Settings.Default.DefaultPrinterPort,
EViewMethods.defaultPrn[0], EViewMethods.defaultPrn[1], EViewMethods.defaultPrn[2], lBox, false, false);
newEntry = comboPrinters.Items[index].ToString();
delPassData del = new delPassData(frmVD.passedNewVal);
del(newEntry);
}
Inside Form3 (formViewDwg) is:
public void passedNewVal(string newPrn) // using the delegate "delPassData" declared in formUserSettings
{
try
{
comboPrinter.Text = newPrn;
}
catch
{
}
}
The error is "Delegate to an instance method cannot have null 'this'".
Try this:
In Form1
Form2 vForm2=new Form2();
vForm2.vForm1=this; //initialize the vForm1 variable of Form2 to this form
vForm2.Show();
and in Form2 define a global public variable of type Form1.
public Form1 vForm1;
you may now be able to play around with any of the property of Form1.
Well I never found out how to send the string from Form2 to Form3, but I found a good solution: When Form2 closes and sends its string to Form1 from "frmUsr_ValueUpdated", it checks to see if Form3 is open. If it is then a public method within Form3 is used to update its comboBox.text as follows. (Form1 = Form1, Form2 = formUserSettings, Form3 = formViewDwg {instance = frmVD})
private void frmUsr_ValueUpdated(object sender, ValueUpdatedEventArgs e) //---added 3-22-12
{
// Update the printer name on Form1 with the new value from formUserSettings
string prnStr = e.NewValue;
string[] parts = prnStr.Split('^'); //the printer name, driver and port were passed by e.NewValue, being separated by a "^"
//---added 5-7-12
EViewMethods.defaultPrn[0] = parts[0]; //printer name
EViewMethods.defaultPrn[1] = parts[1]; //printer driver
EViewMethods.defaultPrn[2] = parts[2]; //printer port
toolStripStatusLabel3.Text = parts[0];
//---added 5-7-12
if (frmVD != null && !frmVD.IsDisposed) //want to send the new printer name now if formViewDwg is already open. If it is not open, then when it is called to open, the formViewDwg constructor will pass the new printer to it.
{
frmVD.ProcessPrinterName(parts[0]); //ProcessPrinterName is a public method inside formViewDwg. Can call here because formViewDwg is already open!
}
}
Inside formViewDwg (Form3) is the public ProcessPrinterName method:
public void ProcessPrinterName(string message)
{
comboPrinter.Text = message;
}
If Form3 (formViewDwg) is not open then the updated printer name will be passed to it whenever an instance is invoked through its constructor parameter list. Printer name will be passed as "string prnName" in the constructor:
public formViewDwg(string currentPath, string currentPartNum, string currentDwgNum,
string prnNameList, string prnDriverList, string prnPortList,
string prnName, string prnDriver, string prnPort, ListBox lstBox, bool usingEngCode, bool engCodeIsEnabled) //---added 3-12-12
{
InitializeComponent();
In (Form1) i have a setting button, when i click on it a new form ( Form2 ) is shown, using these lines of code :
private void b7_Click(object sender, EventArgs e)
{
Form3 frm = new Form3();
frm.Show();
}
In form3, i have 6 text boxes, and two button, Save and Cancel.
What i'm trying to do is to provide this form to the user so he types the neccessary data into the form, then he click the Save Settings button. In Form1, i want to access to these text boxes to get their current values ( when user clicked save settings ). I tried to add a Form4 and named it ( MiddleForm), i added 6 text boxes to it, and in Form3 (The form in the image above) i wrote these line :
private void button2_Click(object sender, EventArgs e)
{
MiddleForm mf = new MiddleForm();
mf.textBox1.Text = keywrd1.Text;
mf.textBox2.Text = keywrd2.Text;
mf.textBox3.Text = keywrd3.Text;
mf.textBox4.Text = keywrd4.Text;
mf.textBox5.Text = keywrd5.Text;
mf.textBox1.Text = thelink.Text;
Close();
}
then i tried to access the values passed to the MiddleForm from Form1 (The form where i need to use the textboxes values), in Form1, i wrote these lines (for debug purposes only)
MiddleForm mf = new MiddleForm();
MessageBox.Show(mf.textBox1.Text); // to see whether there is something
Unfortunately, it seems that nothing is passed to mf.TextBox1
How can i call the current values (Saved using save settings button) of Form3 From Form1 in order to use them in the rest of code.
Any help please on getting this to work ?
Make 6 public properties in your Form3 like that:
public partial class Form3 : Form
{
public string Value1
{
get { return this.keywrd1.Text; }
}
public string Value2
{
get { return this.keywrd2.Text; }
}
...
}
After your Form3 is closed (but before disposed) you can access text values via properties. As pointed in another answer, use ShowDialog instead of Show and close Form3 inside it's own code.
private void b7_Click(object sender, EventArgs e)
{
Form3 frm = new Form3();
frm.ShowDialog();
string value1 = frm.Value1;
...
}
Make public properties in Form3 like this
public string[] Keys
{
get
{
return new string[] { tbKey1.Text, tbKey2.Text, tbKey3.Text,
tbKey4.Text, tbKey5.Text};
}
}
public string Link { get { return tbLink.Text; } }
From Form1 you can access these properties like this
Form3 frm = new Form3();
if (frm.ShowDialog() == DialogResult.OK) {
string[] keys = frm.Keys;
string link = frm.Link;
}
Note: It is important that you use ShowDialog and not Show, since Show does not wait for the other form to close. Also, when "Save settings" is clicked in Form3, set the dialog result
DialogResult = DialogResult.OK;
Close();
so that you can check it in Form1 as shown above.
You need to do this:
var form = Form.ActiveForm as Form3;
String myText = form.txtBoxName.Text;
You should make a public field that provides the values you want to get out of the form. If you go to the source of Form1, you should add in something like this:
public string TextValue1 {
get {return TextBox1.Text;}
}
Now, you can use the Form1.TextBox1 to retrieve a string value from your Textbox.
You could try using ShowDialog it will create your Form as a Model Dialog box, you can then check the DialogResult to know wether the data was saved or the Form was canceled.
i.e.
private void button2_Click(object sender, EventArgs e)
{
Form3 frm = new Form3();
if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
savedSettings = frm.getTextBoxValues();
}
}
Form3
public partial class Form3 : Form
{
string[] textValues = new string[6];
public Form3()
{
InitializeComponent();
}
public string[] getTextBoxValues()
{
return textValues;
}
private void saveSettings_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
textValues[0] = textBox1.Text;
textValues[1] = textBox2.Text;
textValues[2] = textBox3.Text;
textValues[3] = textBox4.Text;
textValues[4] = textBox5.Text;
textValues[5] = textBox6.Text;
this.Close();
}
private void cancelSettings_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
}
I have this code:
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public static string FolderSelect(string txtPrompt)
{
// Now, we want to use the path information to population
// our folder selection initial location
string initialCheckoutPathDir = ("C:\\");
System.IO.DirectoryInfo info =
new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
retPath = "";
DriveRecursion(retPath);
}
else
return "";
}
}
So i have a WindowsForm with a button. The user presses the button, and the FolderBrowserDialog appears. Once the user selects a drive, i want the form (with the button) to close as well.
I haven't been having any luck. Any ideas? Syntax would greatly be appreciated.
After the FolderSelect returns DialogResult.OK, you need to call this.close. So like this:
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.empty;
//Now, we want to use the path information to population our folder selection initial location
string initialCheckoutPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion(retPath);
result = retPath;
//Close this form.
this.Close();
}
return result;
}
Edit:
For some reason your FolderSelect method is static. You should remove the static so it has a reference to the form.
You can just call Close().
Additionally you can open your Form by using ShowDialog() instead of just Show() and set a DialogResult before closing it:
DialogResult = FolderSelect.ShowDialog();
Close();
EDIT:
And your FolderSelect method should be probably void. Better save the result of your FolderSelect dialog to a property.
Since FolderSelect is static, you won't have access to the form variables. So, you have two choices.
A) Make FolderSelect an instance method. Then you can just do this.Close() Mind you, the this is not necessary, I'm just putting it there for clarity.
B) Return a boolean from FolderSelect, and if it's true, inside the button click event, call this.Close()
After FolderSelect, put this.Close();