Open a second Form with a textbox - c#

i open about my Button "ProtokollToolStripMenuItemClick" my second Form! The name of the second Form is INPUTBOX! This second Form has two text boxes and one Button! Now i would like to put in my name and my mobile phone number in the two text boxes and close the window with my button. This two entries i would like to put down in my excel application.(But i donĀ“t now how to get the text box entries). How can i do this?
public partial class MainForm
{
public void ProtokollToolStripMenuItemClick(object sender, EventArgs e)
{
INPUTBOX _Input = new INPUTBOX();
_Input.Show();
//Here I want to put in my new code
//Declaration
Excel.Application ExcelApplication;
Excel._Workbook ExcelWorkbook;
Excel._Worksheet ExcelWorksheet;
try
{
//Start Excel
ExcelApplication = new Excel.Application();
ExcelApplication.Visible = true;
//New Workbook
ExcelWorkbook = (Excel._Workbook)(ExcelApplication.Workbooks.Add(Missing.Value));
ExcelWorksheet = (Excel._Worksheet)ExcelWorkbook.ActiveSheet;
//et cetera

Open the input box with ShowDialog instead of Show, to ensure that your code pauses until the window has been closed.
In your INPUTBOX, create a public property for each of the values you want to return.
In your button click handler, copy the values from the text boxes to the public properties.
Afterwards, in the code shown in your question, you can access the values by accessing _input.NameOfTheNewProperty.

Supposedely you have named your controls txtName and txtPhone you may access them using the following from the calling form.
_Input.txtName.Text
_Input.txtPhone.Text

Related

How to allow excel data modification in manual as well as programmatically?

I am using C# windows application for Excel data add/update. I had added Microsoft.Office.Interop.Excel reference(Reference -> Right Click -> Add Reference -> COM -> Type Libraries -> Microsoft Excel 1X.0 Object Libraries). On my form, I have one panel control panel1, one List-box lstSamples and two button btnAddSample, btnFormatWorksheet.
My sample code is as below:
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class Form1 : Form
{
Microsoft.Office.Interop.Excel.Application excelApp;
Workbook excelWorkBook;
Worksheet excelWorkSheet;
public Form1()
{
InitializeComponent();
LoadExcelFile();
}
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private void LoadExcelFile()
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = true;
excelApp.ScreenUpdating = true;
excelApp.EnableAutoComplete = false;
excelWorkBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
IntPtr excelHwnd = new IntPtr(excelApp.Application.Hwnd);
SetParent(excelHwnd, panel1.Handle);
}
private void btnAddSample_Click(object sender, EventArgs e)
{
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
int lastUsedRow = excelWorkSheet.UsedRange.Rows.Count;
excelWorkSheet.Cells[lastUsedRow + 1, 1] = lstSamples.SelectedItem.ToString();
lstSamples.Items.Remove(lstSamples.SelectedItem);
}
private void btnFormatWorksheet_Click(object sender, EventArgs e)
{
Range chartRange;
excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
chartRange = excelWorkSheet.get_Range("b2", "e9");
chartRange.BorderAround(XlLineStyle.xlContinuous,
XlBorderWeight.xlMedium, XlColorIndex.xlColorIndexAutomatic,
XlColorIndex.xlColorIndexAutomatic);
}
}
Please follow the steps as I mentioned 1. Run the application and add data in "A1" cell (Which is of string type) 2. Again add some data in "A2" cell and Press enter 3. Select one item from lstSamples listbox and click on btnAddSample (Result is like selected item will get added into "A3" cell 4. Try to modify "A1" or "A2" cell data. (Here lstSample is having items of string type like Test1, Test2, Test3,....). If you are able to edit cells then click on btnFormatWorksheet then try to edit any cell.
Why are you referencing the COM DLL? You should be referencing the .Net PIA's - the Primary Interop Assemblies in this location, via the .Net tab in the References window and browse to:
C:\Program Files (x86)\Microsoft Visual Studio [version]\Visual Studio Tools for Office\PIA\Office[version]\Microsoft.Office.Interop.Excel.dll
Only for unit testing do you reference the COM one. See my answer here and how I originally worked it out. It's easy to get confused because in Solution Explorer they are both called the same thing!
If that doesn't work, I originally put this as an answer to save other peoples time being wasted.
Both Ahmed and I cannot reproduce the problem you described with the code you have provided.
See I typed in cells A1 and A2, then I selected an item in the list and clicked the button. Then I select the cell A2 and type Editable.
ps If you can provide the steps to reproduce I'll be happy to take another look at it.
UPDATE:
Your revised steps to reproduce the problem are incorrect, it works for me:
UPDATE 2:
Check if the message pump filters are causing the focus to go to another cell/control:
Excel CustomTaskPane with WebBrowser control - keyboard/focus issues

How to add a ListBox programmatically in a Form

I started out C# very recently and sorry if this question sounds dumb.
How do I add a Listbox in a Form that pops out from a Button click?
Note: The Form isn't the one that's added from the Solution Explorer whereby I can just drag a Listbox from the Toolbox to my Form.
So what I want is to create a ListBox in my file drawer1Form where I can add additional items. Thanks for the help in advance!:)
private void drawer1button_Click(object sender, EventArgs e) // Drawer 1 Button
{
drawer1Form df1 = new drawer1Form();
df1.StartPosition = FormStartPosition.CenterScreen;
df1.Show();
}
public partial class drawer1Form : Form // Creates drawer1Form
{
public drawer1Form()
{
Text = "Drawer 1 ";
}
}
Pretty much the same way as you'd do with any other object.
In the class of your form add a
private ListBox myAwesomeListBox;
Then in the button event handler add something like this:
myAwesomeListBox = new ListBox();
myAwesomeListBox.SuspendLayout();
// set all the properties that you want
myAwesomeListBox.Name = "myAwesomeListBox";
myAwesomeListBox.Location = new Point(...); // place it somewhere
myAwesomeListBox.Size = new Size(...); // give it a size
// etc...
df1.Controls.Add(myAwesomeListBox);
myAwesomeListBox.ResumeLayout();
This should be it.
I highly advise you to do it through the designer first though, and then take a look at the generated code in the form's .Designer.cs file, you'll have a very good understanding after reading through that.

How can I save a dynamically created user control if it contains some buttons in c#?

I am new to C#. I am using windows forms and I have Form1 which contains 2 buttons ( one to create user control at run time and the other creates buttons on user control at run time).
This code creates user control and FlowLayoutPanel (to organize button position) if you click add_UserControl button. And then it creates buttons on FlowLayoutPanel if you click Add_Buttons button and it is all done at run time.
Now in Form1 let's say I created user control and FlowLayoutPanel and then created 5 buttons , how can I save the properties/details of this user control with its FlowLayoutPanel and 5 buttons in SQL database so I can use them later when I run the program? I have been thinking about an idea and I reached the internet but no luck.
Any idea? Please help me. Thank you
public partial class Form1 : Form
{
FlowLayoutPanel FLP = new FlowLayoutPanel();
UserControl uc = new UserControl();
private void add_UserControl_Click(object sender, EventArgs e)
{
uc.Height = 700;
uc.Width = 900;
uc.BackColor = Color.Black;
Controls.Add(uc); //add UserControl on Form1
FLP.Height = 600;
FLP.Width = 800;
FLP.BackColor = Color.DimGray;
uc.Controls.Add(FLP); // add FlowLayoutPanel to UserControl
}
private void Add_Buttons_Click(object sender, EventArgs e)
{
//####### add buttons to FlowLayoutPanel ############
Button dynamicButton = new Button();
dynamicButton.Height = 50;
dynamicButton.Width = 200;
dynamicButton.BackColor = Color.Green;
dynamicButton.ForeColor = Color.Blue;
dynamicButton.Text = "";
FLP.Controls.Add(dynamicButton);
}
}
OK, First you need to create a class that will represent one of the buttons with the properties you need.
class MyButton
{
public string ButtonText {get;set;}
}
Everytime you click and create a button, you actually create an object of this class and add it to a collection or list. Then you would have some other code watching over the collection, and every time it gets a new entry, it creates a new button and sets its Button text to the text property. when a member of list is gone, it removes the button.
If you need more properties to be remembered (color, size, font, ...) you add them to the class as well. If you need for other controls, as well, .... you can always create common parent controls.
Simple.
If you want to be able to reload it, you could define the MyButton class as serializable and store it in xml file, and upon build, reload it.
You should watch into WPF and it's MVVM pattern. It's pretty much similar to it. Also have a look into command pattern, usefull pattern when it commes to this.
You can remember the FlowLayoutsPanels in one SQL table and in another table you could save the buttons which belong to these FlowLayoutPanels.
On Form Load or Application Load, you could check if there are already FlowLayoutPanels and correspending Buttons do exist in the SQL db and if yes then create them, else do nothing.

Creating Edit dialog box in Windows Forms C#

I have Form1.cs which has two buttons say "ADD" and "EDIT".
Clicking "ADD" shows dialog Form2.cs.
Form2 has a TextBox and a ComboBox. Say we enter value "A" in textbox and select "A" from ComboBox.
Then close Form2.
Then when EDIT button is clicked on Form1, Form2 should show up with "A" in textbox and "A" selected in ComboBox.
This is a simple explanation. The real form I am using has around 10-12 different controls including combobox, checkbox, textbox etc.
My main doubt is where and how do we save these control values.
Is there a specific approach to this type of DialogBoxes that I am missing?
Create class, that would store values that you want to pass (let's call it Foo).
Form2 should then have a property. In the setter of the property, set controls:
public partial class Form2 : Form
{
private Foo _bar;
public Foo Bar
{
set
{
_bar = value;
//set your controls here
}
}
On Edit button, set property like this:
Form2 form2 = new Form2();
form2.Bar = bar; //bar contains values to edit
Then put a Save button on Form2, that would save values back from controls to this object.
For every control I would have a field in Foo class, eg. string for textboxes, bool for checkboxes and enum or int for comboboxes (where integer value would equal selected index).
Alternatively, you could use Dictionary class instead and have key and value pair for every control.
You can also have some enum, if your form looks or behaves differently in New and Edit mode.
Your Dialog Form should have a field containing the properties/fields you want, a copy a business object for example. Then you pass it or initialize it in your dialog constructor or Load, depending the behavior you want. From there you can create / initialize your controls.
If you want a built in system you may wanna take a look to the PropertyGrid (which you could embedded in a dialog (to fit your question))
Do you want to just load the last value user entered there?
For instance he writes "text" on the textbox and chooses "A" combobox it should be pre-selected next time you open it?
Edit: Then instead of closing it using Form.Close make it so that it hides. Form1.Hide. Next time it opens values are still saved. Unless application has been closed. In the other hand, users might click on the close button in the windows form. You can either make it "unclickable" throught proprieties or just configure it using events i think.
Create a method on Form2, where you will set values into textBox and select an item in comboBox. Call this method just after instantiating form2 and before showing it.
Example:
public Form2()
{
InitializeComponent();
comboBox1.Items.AddRange(new string[] { "a", "b", "c" });//fill comboBox your way on a loading time
}
public void UpdatingControls(string a, string b)
{
textBox1.Text = a;
comboBox1.SelectedText = b;
}
//on form2;
Form1 f2;
private void OpenForm2Button_Click(object sender, EventArgs e)
{
f2 = new Form2();
f2.UpdatingControls("a", "b"); //a will go into textBox, b will be choosen in comboBox
}
public Form2(string form1Textbox)
{
InitializeComponent();
form2Textbox.Text = form1Textbox;
}

Excel Interop right to left document

I created a new Excel file with C#.
When I open the document all the worksheets are align right to left.
How can I align the worksheet/workbook/window to display left to right grammatically?
Sub leftToRight()
Application.DefaultSheetDirection = xlLTR
ActiveSheet.DisplayRightToLeft = False
End Sub
You can also change the setting through Tools->Options->International. Note that you need to set/unset the Checkbox "View current sheet right-to-left" to change currently open sheets.
Edit: Sorry I accidentally interpreted your question as VBA.
Here is a c# Solution:
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
xlApp.Workbooks.Add(System.Type.Missing);
Excel.Worksheet active = (Excel.Worksheet)xlApp.ActiveSheet;
xlApp.DefaultSheetDirection = (int)Excel.Constants.xlLTR; //or xlRTL
active.DisplayRightToLeft = false;
I would like to introduce my implementation of this feature after i used marg concept and changed it to the right syntax for me:
public void SetWorksheetDirection(Application excel, bool isRTL)
{
Worksheet active = (Worksheet)excel.ActiveSheet;
if (isRTL)
excel.DefaultSheetDirection = (int)XlDirection.xlToRight;
else
excel.DefaultSheetDirection = (int)XlDirection.xlToLeft;
active.DisplayRightToLeft = isRTL;
}
Do this one time to change the default direction:
Alt+F11 to open the VBA editor
Ctrl+G to open the Immediate window
in the Immediate window type Application.DefaultSheetDirection = xlLTR and press Enter
Alt+Q to close the VBA editor
create a new workbook to test it
If you just wanted to organize some of the columns, you could use a line like this:
oWS.Range["A1:B2000"].HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;

Categories

Resources