I have created a C# Windows Form project in Visual Studio and I am trying to work with an Excel workbook via interop.excel. I have created a custom "excel class" and created an object of it in my Form1.
What I am struggling with is whether it is possible to open an excel workbook via a button press, i.e. create the class object from a button press, and then be able to use that object in other button presses.
Two versions of code are shown below. One works,one does not. The one that works just opens the Excel workbook when the program is launched. The other attempts to use a button press on the form to open the workbook after the program is launched. In the code that does not work, the object does not exist in the current context.
Any help on how to make the button press code work is most appreciated!
This code works:
namespace XLtest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ExcelClass ex = new ExcelClass(#"C:\path\TestBook.xlsx", 1);
private void ReadCell_Click(object sender, EventArgs e)
{
ex.ReadCell();
}
...
This code does not:
namespace XLtest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void OpenFile()
{
ExcelClass ex = new ExcelClass(#"C:\path\TestBook.xlsx", 1);
}
private void OpenWorkbook_Click(object sender, EventArgs e)
{
OpenFile();
}
private void ReadCell_Click(object sender, EventArgs e)
{
ex.ReadCell(); // "ex" does not exist in the current context
}
...
You are using a local variable inside ReadCell which has no knowledge of ex.
You could create a variable
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private ExcelClass ex = null; //create your member field here
public void OpenFile()
{
ex = new ExcelClass(#"C:\path\TestBook.xlsx", 1);
}
private void OpenWorkbook_Click(object sender, EventArgs e)
{
OpenFile();
}
private void ReadCell_Click(object sender, EventArgs e)
{
if (ex!= null) {
ex.ReadCell();
} else {
//do nothing, or inform user they have to press other button to open the file
}
}
I think you are asking to be able to reuse the code on another button press? If so would it be an option for you to create a function with the code needed and just call that function inside each button press?
Related
So here is my setup so you can better understand what I am trying to do. I have the following:
Windows Form 1 (Toolbox) with a textbox for the Google Search and a Search Click button that loads the secondary Windows Form (Search Engine). I am wanting to do the following.
Type the search criteria in my text box and clicking on the Search button which will open the secondary Windows Form (Search Engine) which will load the google search on the (Search Engine) form using "WebBrowser1"
Any assistance would be greatly appreciated. If you can provide code instead of where to go that would be best :)
Updated Code: Which opens the Google Search Engine but does not display on the Webbrowser1. Any additional assistance would be appreciated
Form 1 Search button click Code:
namespace Plumchoice_Toolbox
{
public partial class plumchoice_Form1 : Form
{
public plumchoice_Form1()
{
InitializeComponent();
}
private void plumchoice_Form1_Load(object sender, EventArgs e)
{
}
//Search Engine Form 1 added
//// Search Button that opens the Search Engine
private void button18_Click(object sender, EventArgs e)
{
Google_Search.SearchEngineForm1 frm2 = new Google_Search.SearchEngineForm1();
frm2.searchAddress = "http://www.google.com/webhp?hl=en&tab=ww#hl=en&tbo=d&output=search&sclient=psy-ab&q=" + textBox3.Text.Replace(" ", "+");
frm2.Show();
}
Webbrowser1 Code
namespace Google_Search
{
public partial class SearchEngineForm1 : Form
{
public SearchEngineForm1()
{
InitializeComponent();
}
public string searchAddress;
private void PlumChoiceToolboxForm1_Load(object sender, EventArgs e)
{
webBrowser1.Url = new Uri(searchAddress);
}
You can do this: In form1 search button click
This code is for Form1 that has a search text box and a button for start searching. I think (but not sure) it is same as your Toolbox form.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Search_Click(object sender, EventArgs e)//When user clicks on search button
{
SearchEngineForm1 frm2 = new SearchEngineForm1();
frm2.searchAddress = "https://www.google.com/search?q=" + txtSearch.Text.Replace(" ", "+");
frm2.Show();
}
}
And below is the Form2 or SearchEngineForm1 that will open after search button click.
public partial class SearchEngineForm1 : Form
{
public SearchEngineForm1()
{
InitializeComponent();
}
public string searchAddress;
private void SearchEngineForm1_Load(object sender, EventArgs e)
{
webBrowser1.Url= new Uri(searchAddress);
}
}
In your code you have a mistake:
private void PlumChoiceToolboxForm1_Load(object sender, EventArgs e)
{
webBrowser1.Url = new Uri(searchAddress);
}
What is this void? This will never fire. You need to double click on SearchEngineForm1 form (a blank space on form) to add this void to your code:
private void SearchEngineForm1_Load(object sender, EventArgs e)
{
}
Do not forget double click i said. Pasting this only does not help you!
then enter the webBrowser1.Url= new Uri(searchAddress); between its braces {} to have this exactly:
private void SearchEngineForm1_Load(object sender, EventArgs e)
{
webBrowser1.Url= new Uri(searchAddress);
}
I hope the title is clear enough. Let me explain : I am doing a c# Winform App. When I start the app I have my Form 1 which starts, and I have other forms I can open from it by clicking buttons.
The problem is, I have functions in those Forms (Form 2, Form 3, Form 4..) I want to start from the Form 1 .
Currently here's my code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// First Event, when I click in the toolstrip menu, I open the Form2 ("Ligne3")
private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
{
var Ligne3 = new Ligne3();
Ligne3.Show();
}
Then, I have components in the Form2 (textboxs, buttons, functions etc)
public partial class Ligne3 : Form
{
public Ligne3()
{
InitializeComponent();
}
private void Ligne3_Load(object sender, EventArgs e)
{
//Some code
}
}
//Function I want to call from the Form1
public void send_email()
{
//Some code
}
How can I start my " send_email() " function from the Form1 (for example during Load Event) ?
Assign the values of Form2 or any other objects/variables to Linge3 object before calling show. Values which are needed in send_email() to be assigned before calling send_email(). Something like below.
private void ligne3ToolStripMenuItem_Click(object sender, EventArgs e)
{
var ligne3 = new Ligne3();
//define variables/properties in Ligne3 for all values to be passed
//then assign them with corresponding values
ligne3.Value1 = objForm2.Value1;
ligne3.Value2 = objForm2.Value2;
ligne3.Value3 = objForm2.textBox1.Text;
ligne3.Value3 = objForm2.checkBox1.Value;
//and so on
ligne3.send_email();
ligne3.Show();
}
If you are clicking a buttons on Form1, to start and open forms 2,3,4 etc, and in those btn_click handlers you are creating a new form2, 3,3,4. Then you will have a reference to each form and and can therefore just call the respective public method on the instance just created. eg
public class Form1
{
private Form2 subForm2;
private void OpenForm2_Click(object sender, eventargs e)
{
subForm2 = new Form2();
subForm2.Show()
}
private void sendEmailBtn_Click(object sender, EventArgs e)
{
subForm2.Send_email();
}
}
This are many things wrong with the above from a design point of view but i'm just using it to present the idea.
If you are creating the instance of Form2,3,4 etc outside of Form1's instantiation, then you would need some form of Constructor or property injection to provide the instance references.
i am working with my c# windows aplication, in this application form named "patients" and other named "patientsDuplicatedName" which contain datagridview and load all Duplicated Patients Name (this and works fine,,)
but i want when slsected Row get all values into form "patients" at run time (already open) without creating new form "Patients"..
Below is the code I am referring to:
public partial class frmPatientsNameDuplicated : Form
{
PatientFiles frmPatientsFiles =new PatientFiles() ;
public frmPatientsNameDuplicated()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
frmPatientsFiles.txtFileNum.Text = this.dgvPatientsName.CurrentRow.Cells[0].Value.ToString();
frmPatientsFiles.txtArbName.Text = this.dgvPatientsName.CurrentRow.Cells[1].Value.ToString();
frmPatientsFiles.txtEngName.Text = this.dgvPatientsName.CurrentRow.Cells[2].Value.ToString();
//frmPatientsFiles.show();//this line is creating new form and run
this.Close();
}
}
sorry about my bad english & thanks in advance
The commented out line frmPatientsFiles.show() has a comment that says that the line is creating a new form. It is not. It is simply displaying a form that has been previously created on line PatientFiles frmPatientsFiles = new PatientFiles(); This appears to be creating the new form that you don't want. If you already have an existing form that you want to update, reference that form from your btnOk_Click event handler. To do this, you probably want to pass in a reference to the (existing) form to your class, either via the constructor or some other method/property. I hope I have understood your question correctly.
i found same issue here :
Pass data to a existing form
so my code become
public partial class frmPatientsNameDuplicated : Form
{
PatientFiles frmPatientsFiles = Application.OpenForms["PatientFiles"] as PatientFiles;
public frmPatientsNameDuplicated()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
frmPatientsFiles.txtFileNum.Text = this.dgvPatientsName.CurrentRow.Cells[0].Value.ToString();
frmPatientsFiles.txtArbName.Text = this.dgvPatientsName.CurrentRow.Cells[1].Value.ToString();
frmPatientsFiles.txtEngName.Text = this.dgvPatientsName.CurrentRow.Cells[2].Value.ToString();
this.Close();
}
}
I want to re-use a Form, and the behaviour of a button should change, depending if the form was opened with arguments or not.
The form is opened with this code:
public partial class FollowUp : Form
{
public FollowUp(string so)
{
InitializeComponent();
[code]
}
}
and outside the form code is the button click code:
private void btnSaveChanges_Click(object sender, EventArgs e)
{
if (string so != "")
{
some code
}
}
How can I get the button click event to recognize if there was an argument when opening the form? (the string 'so' is not recognized in the button code).
Well, your FollowUp class could be defined as
public partial class FollowUp : Form
{
private string _So;
public FollowUp(string so)
{
InitializeComponent();
_So = so;
[code]
}
private void btnSaveChanges_Click(object sender, EventArgs e)
{
if (_So != "")
{
some code
}
}
}
Key idea: store your so variable passed in coustructor into class private field _So and use this sotred value when it is needed.
I Made an application. The Main form Name is Form1.
And the other Form is called PoP.
public partial class pops : Form
{
public pops()
{
InitializeComponent();
CenterToScreen();
}
private void pops_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void lblAdminNo_Click(object sender, EventArgs e)
{
}
}
Make two public properties on popup form and retrieve them from parent form.
string username = string.Empty;
string password = string.Empty;
using (LoginForm form = new LoginForm ())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.Ok)
{
username = form.Username;
password = form.Password;
}
}
It all depends on from where are you calling the Pop form.
If it is called from the Form1 itself, then the Popform's object itself would provide you the value.
Pop popFrm = new Pop();
if(popFrm.ShowDialog() == Ok)
{
string userName = popFrm.TextBox1.Text;
}
If the Pop is invoked from a different area/part of application, you may have to store it somewhere common to both the forms.
This can be done through events. This approach is particularly useful when data to be posted even when the child form is kept open.
The technique is- From parent form, subscribe to a child from event. Fire the event when child form closes, to send data
----- SAMPLE CODE-----
Note: In the Parent Form add a Button:button1
namespace WindowsFormsApplication2
{
public delegate void PopSaveClickedHandler(String text);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Pops p = new Pops();
p.PopSaveClicked += new PopSaveClickedHandler(p_PopSaveClicked);//Subscribe
p.ShowDialog();
}
void p_PopSaveClicked(string text)
{
this.Text = text;//you have the value in parent form now, use it appropriately here.
}
}
Note: In the Pops Form add a TextBox:txtUserName and a Button:btnSave
namespace WindowsFormsApplication2
{
public partial class Pops : Form
{
public event PopSaveClickedHandler PopSaveClicked;
public Pops()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if(PopSaveClicked!=null)
{
this.PopSaveClicked(txtUserName.Text);
}
}
}
}
Summary:
1.Add a delegate(place where it available to both parent and child form) :
public delegate void PopSaveClickedHandler(String text);
2.In form:Pops, Add an event:
public event PopSaveClickedHandler PopSaveClicked;
3.Subscribe to the event in Parent Form:
p.PopSaveClicked += new PopSaveClickedHandler(p_PopSaveClicked);
4.Invoke the event in form:Pops Save Button Click
if(PopSaveClicked!=null)
{
this.PopSaveClicked(txtUserName.Text);
}
You can send data to the form object before you display it. Create a method to call, send the info through the constructor... etc.