How to Inherit button with code from form1 to form2 - c#

I have a main form which is called form and a second form called form2. Form contains a button with a coded function inside. Now on my form2 I have the same button which performs the same function on form or which I want it to perform the same function as form1.
On form2 I have created a button of which I want it to use the same function from the form1. Now I want to be able to click the button from form2 and it calls the button funtion from form1.
I have done this but I don't know how I can make it work
Form1 (mainform)
public Button newButton
{
get
{
return btnNewfile;
}
}
public void SetLanguage(string cbolang)
{
cboLanguage.SelectedValue = cbolang;
}
Form2
public frmMain_Page _frmMainform;
public FrmLanguage(frmMain_Page _frmMainform)
{
InitializeComponent();
this._frmMainform = _frmMainform;
}
public frmMain_Page _Main
{
get;
set;
}
//from this button I can't get the main button from the main form
private void btnCreatFile_Click(object sender, EventArgs e)
{
_frmMainform.newButton.btnNewfile;
//Error 19 'System.Windows.Forms.Button' does not contain a definition for 'btnNewfile' and no extension method 'btnNewfile' accepting a first argument of type 'System.Windows.Forms.Button' could be found (are you missing a using directive or an assembly reference?)
}
this is the button with coded function. am trying to take it from this button
private void btnNewfile_Click(object sender, EventArgs e)
{
_frmMainform.newButton;
XmlDocument _doc = new XmlDocument();
FileInfo _fileInfo = new FileInfo(txtInputfile.Text);
_InputFileName = _fileInfo.Name;
_InputFileSourceDirectory = _fileInfo.DirectoryName;
_InputFileExternsion = _fileInfo.Extension;
_OutFileName = cboLanguage.SelectedItem.ToString() + "-language.resx";
string outputFilePath = txtInputfile.Text.Replace(_InputFileName, _OutFileName);
File.Copy(txtInputfile.Text, outputFilePath);
string text = File.ReadAllText(outputFilePath);
XDocument doc = XDocument.Load(outputFilePath);
foreach (var valueNode in doc.Descendants("data").SelectMany(n => n.Elements("value")))
{
valueNode.Value = string.Empty;
}
foreach (var commentNode in doc.Descendants("data").SelectMany(n => n.Elements("comment")))
{
commentNode.Value = DeleteBetween(commentNode.Value, "Font");
commentNode.Value = DeleteBetween(commentNode.Value, "DateStamp");
commentNode.Value = DeleteBetween(commentNode.Value, "Comment");
}
doc.Save(outputFilePath);
txtOutputfile.Text = _InputFileSourceDirectory + "\\" + _OutFileName;
_doc.Load(outputFilePath);
string xmlcontents = _doc.InnerXml;
//lblversion.Text = updateversion.ToString();
}

private void btnCreatFile_Click(object sender, EventArgs e)
{
// because newButton returns btnNewfile
// You can access btnNewLife by : _frmMainform.newButton
_frmMainform.newButton.Text = "My Button";
}
Also your newButton returns a Button object.
A Button object dose not have a child Button.
So you just need to access newButton to get btnNewLife.

Related

How do I display text from another window in windows form c#?

The goal is to display the text from user input using radio button and combo box. I'm using Visual Studio, by the way.
This is the code from the first window:
private void btn_apply_Click(object sender, EventArgs e)
{
firstName = tbx_firstName.Text;
middleName = tbx_middleName.Text;
lastName = tbx_lastName.Text;
completeName = firstName + " " + middleName + " " + lastName + " ";
gender = lbl_gender.Text;
level = lbl_level.Text;
status = lbl_status.Text;
if (rbtn_male.Checked)
{
lbl_gender.Text = rbtn_male.Text.ToUpper();
}
else
{
lbl_gender.Text = rbtn_female.Text.ToUpper();
}
//Level
if (rbtn_gradeEleven.Checked)
{
lbl_level.Text = rbtn_gradeEleven.Text.ToUpper();
}
else if (rbtn_gradeTwelve.Checked)
{
lbl_level.Text = rbtn_gradeTwelve.Text.ToUpper();
}
else if (rbtn_iST.Checked)
{
lbl_level.Text = rbtn_iST.Text.ToUpper();
}
else if (rbtn_iSM.Checked)
{
lbl_level.Text = rbtn_iSM.Text.ToUpper();
}
else
{
}
//Admission Status
cbx_status.SelectedItem.ToString();
//Form2
this.Hide();
Form2 output = new Form2();
output.Show();
Meanwhile, this is the code for the second window (Result):
private void Form2_Load(object sender, EventArgs e)
{
lbl_displayName.Text = Form1.completeName;
lbl_displayGender.Text = Form1.gender;
lbl_displayLevel.Text = Form1.level;
lbl_displayStatus.Text = Form1.status;
}
Thank you!
when Form2 should display elements from Form1, the former surely has to have a reference to the latter. So start giving Form2 a reference to your Form1-instance, e.g. using a constructor-arg on Form2.
However usually you don't want to pass controls or forms around, but just specific values within those. In your case those are the gender, name the level and the status. So just provide those arguments to Form2, not the entire Form1-instance:
class Form2 : Form
{
private readonly string name; // ...
public Form2(string name, string status, string level, string gender)
{
this.name = name;
// ...
}
}
Now you can easily access those variables within your Load-event:
private void Form2_Load(object sender, EventArgs e)
{
lbl_displayName.Text = this.name;
lbl_displayGender.Text = this.gender;
lbl_displayLevel.Text = this.level;
lbl_displayStatus.Text = this.status;
}
Change:
Form2 output = new Form2();
output.Show();
To:
Form2 output = new Form2();
output.Show(this); // <-- Form1 as the Owner of output
Now in Form2, simply cast .Owner back to Form1:
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = (Form1)this.Owner;
lbl_displayName.Text = f1.completeName;
lbl_displayGender.Text = f1.gender;
lbl_displayLevel.Text = f1.level;
lbl_displayStatus.Text = f1.status;
}

If statement triggered by button click

Here is my code:
public static string name;
private void openWindow(object sender, EventArgs e)
{
if (button_name1.PerformClick){
name = "name1";
}
if (button_name2.PeformClick)
{
name = "name2";
}
else
{
name = "name3";
}
this.Hide();
Form2 form2 = new Form2();
form2.ShowDialog();
}
So I have three buttons, each of them should open a new identical window when it is clicked. But each button has to save a different name in a string (name).
My goal in this if condition is exactly that, but VS2017 says PeformClick cannot be converted to the type bool.
Second, it means that button doesn't have a definition for PeformClick.
How can I solve this?
Or have I tried it completely wrong from the beginning?
Is this "openWindow" attached as click-handler to all three buttons? Then "sender" is that specific button, you just need to cast it. You could set the .Tag property beforehand and read its value in the handler.
private void openWindow(object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
name = clickedButton.Tag;
// create form etc
}
Assuming you have tree buttons and all of their click event is attached to openWindow
something below can work for you.
public static string name;
private void openWindow(object sender, EventArgs e)
{
Button senderButton = (Button)sender;
if (senderButton == button1)
{
name = "name1";
}
else if (senderButton == button2)
{
name = "name2";
}
else
{
name = "name3";
}
this.Hide();
Form form2 = new Form();
form2.ShowDialog();
}
Actually this is the complete code of the approach which is also offered by #Hans Kesting.

Using variables in primary Form from secondary From

I am having issues transfering data points from one form to another. I have made sure that the button inside of addTagsForm has a public modifier.
I've looked at multiple solutions of using data values from one form to another and I must be missing something from them.
Here is what I have in Form1:
//Inside Form1
XMLDocGen.PLCData PLC = new XMLDocGen.PLCData();
List<XMLDocGen.TagData> tags = new List<XMLDocGen.TagData>();
AddTagsForm addTagsForm = new AddTagsForm();
addMoreTagsSelected = addTagsForm.addMoreTagsEnabled;
if(addMoreTagsSelected)
{
for(int i= 0; i < 8; i++)
tags.Add(new XMLDocGen.TagData(addTagsForm.addTags[i], addTagsForm.addDataTypes[i], addTagsForm.addElemSizes[i], addTagsForm.addElemCounts[i]));
}
Here is what is inside of addTagsForm
public void button1_Click(object sender, EventArgs e)
{
addMoreTagsEnabled = true;
var tagNames = new List<TextBox>() { tagNameBoxAMT1, tagNameBoxAMT2, tagNameBoxAMT3, tagNameBoxAMT4, tagNameBoxAMT5, tagNameBoxAMT6, tagNameBoxAMT7, tagNameBoxAMT8 };
var dataTypes = new List<ComboBox>() { dataTypeBoxAMT1, dataTypeBoxAMT2, dataTypeBoxAMT3, dataTypeBoxAMT4, dataTypeBoxAMT5, dataTypeBoxAMT6, dataTypeBoxAMT7, dataTypeBoxAMT1 };
var elemSizes = new List<TextBox>() { elemSizeBoxAMT1, elemSizeBoxAMT2, elemSizeBoxAMT3, elemSizeBoxAMT4, elemSizeBoxAMT5, elemSizeBoxAMT6, elemSizeBoxAMT7, elemSizeBoxAMT8 };
var elemCounts = new List<TextBox>() { elemCountBoxAMT1, elemCountBoxAMT2, elemCountBoxAMT3, elemCountBoxAMT4, elemCountBoxAMT5, elemCountBoxAMT6, elemCountBoxAMT7, elemCountBoxAMT8 };
for (int i = 0; i < 8; i++)
{
addTags.Add(tagNames[i].Text);
addDataTypes.Add(dataTypes[i].Text);
addElemSizes.Add(elemSizes[i].Text);
addElemCounts.Add(elemCounts[i].Text);
}
this.Hide();
}
I have checked to make sure each list is populated correctly and they are. As well as the Lists being public. The problem is trying to grab these values from Form1. There has to be something simple that I'm missing! Thanks for the help!
With the reference of your comment i've generated an idea for you. By writing a simple public Action in your Second form Form2 you can achieve your goal. Below i'm showing an example:
Declare a public Action in your Form2 global scope with your desired collection type, like this way:
public Action<List<TextBox>, List<ComboBox>> actGetCollection;
Keep a method with some of your desired collection type parameter in your Form1 like this way:
private void GetCollectionItems(List<TextBox> addTags, List<ComboBox> addDataTypes)
{
//you will get your list items here and do whatever you want with these
}
In your Form1 from where your second form will open bind your GetCollectionItems() method with your Action in Form2 (assuming you do this in a button's click event) like this way:
private void button1_Click(object sender, EventArgs e)
{
//create an instance of your Form2 Form
Form2 obj = new Form2();
//bind your function with the action
obj.actGetCollection = GetCollectionItems;
//then call your Form2's ShowDialog() method to show the form
obj.ShowDialog();
//now your Form2 is opended
}
Now in your Form2's button_click event do this:
public void button1_Click(object sender, EventArgs e)
{
addMoreTagsEnabled = true;
var tagNames = new List<TextBox>() { tagNameBoxAMT1, tagNameBoxAMT2, tagNameBoxAMT3, tagNameBoxAMT4, tagNameBoxAMT5, tagNameBoxAMT6, tagNameBoxAMT7, tagNameBoxAMT8 };
var dataTypes = new List<ComboBox>() { dataTypeBoxAMT1, dataTypeBoxAMT2, dataTypeBoxAMT3, dataTypeBoxAMT4, dataTypeBoxAMT5, dataTypeBoxAMT6, dataTypeBoxAMT7, dataTypeBoxAMT1 };
var elemSizes = new List<TextBox>() { elemSizeBoxAMT1, elemSizeBoxAMT2, elemSizeBoxAMT3, elemSizeBoxAMT4, elemSizeBoxAMT5, elemSizeBoxAMT6, elemSizeBoxAMT7, elemSizeBoxAMT8 };
var elemCounts = new List<TextBox>() { elemCountBoxAMT1, elemCountBoxAMT2, elemCountBoxAMT3, elemCountBoxAMT4, elemCountBoxAMT5, elemCountBoxAMT6, elemCountBoxAMT7, elemCountBoxAMT8 };
for (int i = 0; i < 8; i++)
{
addTags.Add(tagNames[i].Text);
addDataTypes.Add(dataTypes[i].Text);
addElemSizes.Add(elemSizes[i].Text);
addElemCounts.Add(elemCounts[i].Text);
}
//call the action
if(actGetCollection != null)
actGetCollection(addTags, addDataTypes);
this.Hide();
}
When your Form2 wil disappear your code will get back to your Form1's event from where you're called your Form2. Now in your GetCollectionItems() you've the collection items that you're wanted.
You can set stuff in your second form from your first:
class Form1
{
...
public void OnButtonPress()
{
var anotherForm = new Form2();
anotherForm.AList = mylist;
anotherForm.BList = myBList;
anotherForm.ShowDialog();
}
}
Alternatively, you could create a class that encapsulates everything you want to pass between the two and so only pass on thing. If it's mandatory I would put it in Form2's constructor:
public Form2(MyImportantStuff stuff)

C# - How to save a string entered in Form2 in Form1

I get the default path from the registry for the Steam installation. But if someone has their games installed to a different folder, the user has to enter it in the Configure form. When the form gets closed, that path entered(from the folder browser or by typing the path in manually) should get saved to a string in the main form and should enable a different Combobox which turns on different buttons. I somehow managed to do the save to the mainform string, but the 2nd combobox doesn't seem to turn on. How can I do it correctly?
** MAIN FORM **
public string NewPath { get; set; }
private ConfigForm otherForm;
string InstallPath = (string)Registry.GetValue(#"HKEY_CURRENT_USER\SOFTWARE\Valve\Steam", "SteamPath", null);
private void PortalHammerButton_Click(object sender, EventArgs e)
{
Process.Start(InstallPath + #"\SteamApps\common\Portal\bin\hammer.exe");
}
private void Gamedropdown_SelectedIndexChanged(object sender, EventArgs e)
{
if (Gamedropdown.Text == "Portal") // When Portal is selected
{
// Enable the Portal SDK buttons
PortalHammerButton.Visible = true;
PortalModelViewerButton.Visible = true;
PortalFacePoserButton.Visible = true;
// Disable the CS:GO SDK buttons
csgoFacePoserButton.Visible = false;
csgoHammerButton.Visible = false;
csgoModelViewerButton.Visible = false;
}
else if (Gamedropdown.Text == "CS:GO") // When CS:GO is selected
{
// Disable Portal SDK buttons
PortalHammerButton.Visible = false;
PortalModelViewerButton.Visible = false;
PortalFacePoserButton.Visible = false;
// Enable CS:GO SDK buttons
csgoFacePoserButton.Visible = true;
csgoHammerButton.Visible = true;
csgoModelViewerButton.Visible = true;
}
}
private void ConfigureButton_Click(object sender, EventArgs e)
{
var configdialog = new ConfigForm();
configdialog.Show();
}
private void PortalDifferentHammerButton_Click(object sender, EventArgs e)
{
Process.Start(NewPath + #"\SteamApps\common\Portal\bin\hammer.exe");
}
private void NewDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
if (NewDropDown.Text == "Portal") // When Portal is selected
{
// Enable the Portal SDK buttons
PortalDifferentHammerButton.Visible = true;
PortalDifferentModelViewerButton.Visible = true;
PortalDifferentFacePoserButton.Visible = true;
// Disable the CS:GO SDK buttons
DifferentCSGOFaceposerButton.Visible = false;
DifferentCSGOHammerButton.Visible = false;
DifferentCSGOModelViewerButton.Visible = false;
}
else if (NewDropDown.Text == "CS:GO") // When CS:GO is selected
{
// Disable the Portal SDK buttons
PortalDifferentFacePoserButton.Visible = false;
PortalDifferentHammerButton.Visible = false;
PortalDifferentModelViewerButton.Visible = false;
// Enable the CS:GO SDK buttons
DifferentCSGOModelViewerButton.Visible = true;
DifferentCSGOHammerButton.Visible = true;
DifferentCSGOFaceposerButton.Visible = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.Close();
}
}
}
**CONFIGURE FORM**
public partial class ConfigForm : Form
{
public ConfigForm()
{
InitializeComponent();
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
public void DifferentFolderBrowseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string newpath = fbd.SelectedPath;
NewPathBox.Text = newpath;
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
public void CloseButton_Click(object sender, EventArgs e)
{
this.Hide();
Form1 frm1 = new Form1();
frm1.Gamedropdown.Visible = false;
frm1.NewDropDown.Visible = true;
}
}
}
Any help would be appriciated.
Look at your ConfigForm. Here's your problem:
public ConfigForm()
{
InitializeComponent();
Form1 frm1 = new Form1();
frm1.NewPath = NewPathBox.Text;
}
What you're doing on your Form1 (which I'm guessing is your Main form) is creating a new instance of your ConfigForm and showing it. What you're doing in your ConfigForm is creating a new main form and setting the NewPath = to the value entered on your config form. The problem is this new Form1 is NOT the Form1 that created the ConfigForm. The Form1 that created your config form is not the one getting updated by your code, some arbitrary new Form1 that you create is the one getting updated. This is why your code isn't working as you expected.
Here's the approach I would take. Add a NewPath variable to your ConfigForm just like you have in Form1. Then, add a FormClosing method to FormConfig. Do something like this:
private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
{
NewPath = NewPathBox.Text;
}
Then, change your code on Form1 to this:
private void button1_Click(object sender, EventArgs e)
{
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.ShowDialog();
this.NewPath = cfgfrm.NewPath;
}
What this code is doing is creating and showing a new ConfigForm on your Form1 when you click button1. Then, when your user closes the FormConfig, the form saves the textbox value to the NewPath variable on the FormConfig. Then, once the form is closed, the code on Form1 resumes. Form1 then looks at the NewPath value that was saved when the user closed the FormConfig. Form1 grabs this new NewPath value and puts it in its own NewPath variable.
EDIT
To show/hide comboboxes:
private void button1_Click(object sender, EventArgs e)
{
ConfigForm cfgfrm = new ConfigForm();
cfgfrm.ShowDialog();
this.NewPath = cfgfrm.NewPath;
Gamedropdown.Visible = false;
NewDropDown.Visible = true
}
I'm not sure why you are making the secondary form so complicated. You don't need a pointer to it after you use it and you should be closing instead of hiding. Try this:
class ConfigForm : Form
{
public string newPath = null;
public void CloseButton_Click(object sender, EventArgs e)
{
newPath = NewPathBox.Text;
}
public void CloseButton_Click(object sender, EventArgs e)
{
Close();
}
}
...and in your main form:
public partial class Form1 : Form
{
string steamPath = null; // set to starting path
private void ConfigureButton_Click(object sender, EventArgs e)
{
bool valueChanged = false;
using (ConfigForm form = new ConfigForm())
{
form.newPath = null;
form.ShowDialog();
if (form.newPath != null)
{
steamPath = form.newPath;
valueChanged = true;
}
}
if (valueChanged)
{
// here is where you would handle reloading and changing the ComboBoxes
}
}
}
This will more cleanly return the new string. Whatever you want to do as a result of having changed the path can be done after you have disposed of the config form (bringing it up with the "using" conditional automatically does the disposal for you)

Trying to grab information from a Data Table in Form 2 and set Textboxes in Form 1 using C#

I have two forms (Form 1 and Form 2), I am successful in passing a data table from Form 1 to Form 2 by filling a data grid view in a dialog box. I also have an event handler to capture double click events on a selected row. When the event occurs I want to set textboxes in form 1 from the click event in form 2. No matter what I try I can not seem to show the text inside the textboxes. Below is my code:
//Code begins here
//....Function to fill data table from form 1 and pass to form 2
private void buttonNewEntryLookUp_Click(object sender, EventArgs e)
{
try
{
cs.Open();
da.SelectCommand = new SqlCommand("Select ctx_customername AS Customer, ctx_contactname AS Contact, ctx_custaddress1 AS Address, ctx_custcity AS City, ctx_custstate AS State, nno_custzip AS ZIP, ctx_custemail AS Email FROM Customers WHERE nno_custphone = '" + maskedTextBoxNewLogTel.Text + "'", cs);
dt.Clear();
da.Fill(dt);
}
catch
{
MessageBox.Show("Connection to Database could not be established, please close this application and try again. If problem continues please contact server Admin. Thank you.", "AAMP");
//Display this message if connection could not be made
}
cs.Close();//close connection to db
if (dt.Rows.Count == 0)//if there are no returned results then this must be a new entry into the database
{
MessageBox.Show("Phone Number Not Found in Database.", "AAMP");
}
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
}
}
public void getContactInfo(string[] contactInfo)
{
textBoxNewLogCustomerName.Text = contactInfo[0];
textBoxNewLogContactName.Text = contactInfo[1];
textBoxNewLogAddress.Text = contactInfo[2];
textBoxNewLogCity.Text = contactInfo[3];
textBoxNewLogState.Text = contactInfo[4];
textBoxNewLogZIP.Text = contactInfo[5];
textBoxNewLogEmail.Text = contactInfo[6];
}
//code for form 2
public partial class Form2 : Form
{
/*Globals for Form 2*/
DataTable g_dt;
public Form2(DataTable dt)
{
InitializeComponent();
dataGridViewLookUp.DataSource = dt;
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Form1 form1 = new Form1();
string[] contactInfo = new string[7];
contactInfo[0] = Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]);
contactInfo[1] = Convert.ToString(g_dt.Rows[e.RowIndex]["Contact"]);
contactInfo[2] = Convert.ToString(g_dt.Rows[e.RowIndex]["Address"]);
contactInfo[3] = Convert.ToString(g_dt.Rows[e.RowIndex]["City"]);
contactInfo[4] = Convert.ToString(g_dt.Rows[e.RowIndex]["State"]);
contactInfo[5] = Convert.ToString(g_dt.Rows[e.RowIndex]["ZIP"]);
contactInfo[6] = Convert.ToString(g_dt.Rows[e.RowIndex]["Email"]);
form1.getContactInfo(contactInfo);//return the row number being clicked.
this.Close();
}
}
I am successful in passing the data table to form 2 and capturing the correct information to fill the string array but when I pass the string array back by calling the getContactInfo function I can not seem to set my textboxes with the data. Can someone please, please help!
Thanks.
Your OP is a little vague, but I have some code that does this, takes some data in form 2 and sends it back to form 1.
Here's the code from form1:
private void btnGroupNameLookup_Click(object sender, EventArgs e)
{
//instantiate an instance of the grp name lookup form
frmGroupNameLookup lookupName = new frmGroupNameLookup();
//add an event handler to update THIS form when the lookup
//form is updated. (This is when LookupUpdated fires
lookupName.GroupNamesFound += new frmGroupNameLookup.LookupHandler(lookupName_GroupNamesFound);
//rc.ReconCFUpdated += new ReconCaseFileChecklist.ReconCFListHandler(ReconCFForm_ButtonClicked);
lookupName.Show();
}
void lookupName_GroupNamesFound(object sender, GroupNameLookupUpdateEventArgs e)
{
//update the list boxes here
foreach (string s in e.Parents)
{
lstFilteredGroupParents.Items.Add(s);
}
foreach (string s in e.Groups)
{
lstFilteredGroups.Items.Add(s);
//link supgroups and plan ids
GetFilteredSubgroupNos(s);
GetFilteredPlanIds(s);
}
//ensure dupes are stripped out
//filter out duplicates
var noDupeSubgroups = subgroupList.Distinct().ToList();
noDupeSubgroups.Sort();
foreach (string s in noDupeSubgroups)
{
lstFilteredSubgroups.Items.Add(s);
}
var noDupePlanIDs = planIDList.Distinct().ToList();
noDupePlanIDs.Sort();
foreach (string s in noDupePlanIDs)
{
lstFilteredPlanID.Items.Add(s);
}
}
From Form2
public partial class frmGroupNameLookup : Form
{
//add a delegate, the GroupNameLookupUpdateEventArgs class is defined at the bottom
//of this file
public delegate void LookupHandler(object sender, GroupNameLookupUpdateEventArgs e);
//add an event of the delegate type
public event LookupHandler GroupNamesFound;
//this event closes the forms and passes 2 lists back to form 1
private void btnCommit_Click(object sender, EventArgs e)
{
List<string> prnt = new List<string>();
List<string> grp = new List<string>();
//get selected rows
if (grdLookup.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in grdLookup.SelectedRows)
{
prnt.Add(row.Cells[0].Value.ToString());
grp.Add(row.Cells[1].Value.ToString());
}
//filter out duplicates
var noDupeParentGroups = prnt.Distinct().ToList();
noDupeParentGroups.Sort();
// instance the event args and pass it each value
GroupNameLookupUpdateEventArgs args =
new GroupNameLookupUpdateEventArgs(noDupeParentGroups, grp);
// raise the event with the updated arguments
this.GroupNamesFound(this, args);
this.Dispose();
}
}
}
public class GroupNameLookupUpdateEventArgs : System.EventArgs
{
// add local member variables to hold text
private List<string> mParents = new List<string>();
private List<string> mGroups = new List<string>();
// class constructor
public GroupNameLookupUpdateEventArgs(List<string> sParents, List<string> sGroups)
{
this.mParents = sParents;
this.mGroups = sGroups;
}
// Properties - Viewable by each listener
public List<string> Parents
{
get { return mParents; }
}
public List<string> Groups
{
get { return mGroups; }
}
}
Simple. Make the contact information a method public in Form2 and then just assign it after the ShowDialog() in form1.
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
getContactInfo(form2.ContactInfoFromForm2);
}
You're passing the datatable into the constructor of Form2:
Form2 form2 = new Form2(dt);
You could instead pass a reference to the entire Form1:
Form2 form2 = new Form2(this);
Then you make public methods on Form1 that Form2 can use to update data. Something like this:
//In Form1
public DataTable getDataTable(){
//return datatable
}
public void setTextBoxValue(string Value){
//Set the value
}
And then in Form2
private Form1 _form1;
public Form2(Form1 form1){
_form1 = form1;
dataGridViewLookUp.DataSource = _form1.getDataTable();
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
_form1.setTextBoxValue(Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]));
//etc
}
Are you getting an error or is the data just not displaying. Maybe try a ToString() method behind each stringarray index in the getcontactinfo method. (i.e. contactInfo[0].ToString();)

Categories

Resources