I'm trying to send a string from form2 to form3 to pre-load the form with info. I call a method on form3 accepting the string which starts a linq query to set the controls on the form. I get a NullReferenceException was unhandled in the first
foreach on recipeNameTextBox.Text = a.RecipeName;
I can see that the query ran and the info is in a.RecipName. I think I might be getting this error because the control hasn't been drawn yet. Any Ideas how to get around this? Form2 code is here:
private void updateButton_Click(object sender, EventArgs e)
{
Form3 Frm3 = new Form3();
Frm3.Show();
this.Hide();
Frm3.takeInputFromForm2(recipeLabel.Text);
}
form3 code here:
public void takeInputFromForm2(string incommingUpdateRecipe)
{
Query updateRecipe = new Query();
IEnumerable<Recipe> newrecipe = updateRecipe.getRecipeInfo(incommingUpdateRecipe);
foreach (var a in newrecipe)
{
recipeNameTextBox.Text = a.RecipeName;
nationalityTextBox.Text = a.Nationality;
eventTextBox.Text = a.Event;
sourceTextBox.Text = a.Source;
typeTextBox.Text = a.Type;
ServingsTextBox.Text = a.Servings;
}
foreach (var b in newrecipe)
{
userRatingTextBox.Text = Convert.ToString(b.UserRating);
familyRatingTextBox.Text = Convert.ToString(b.FamilyRating);
healthRatingTextBox.Text = Convert.ToString(b.HealthRating);
easeOfCookingTextBox.Text = Convert.ToString(b.CookingTime);
cookingTimeTextBox.Text = Convert.ToString(b.CookingTime);
}
foreach (var c in newrecipe)
{
ingredientComboBox.Items.Add(c.RecipeIngredient);
}
}
You are probably missing the InitializeComponent in your Form3 constructor.
Related
I cant realize what is wrong here so that listBox is empty, instead of having one list inside?(Probably very easy to solve but I cant get it on my own yet)
public List<Karta> ubaciUListu()
{
List<Karta> Lista1 = new List<Karta>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
Karta k = new Karta(0,"","");
// k.Id =(int)row.Cells[0].Value;
k.Pojam =(string) row.Cells[1].Value;
k.Opis = (string)row.Cells[2].Value;
Lista1.Add(k);
}
return Lista1;
}
private void btnNovaF_Click(object sender, EventArgs e)
{
//ubaciUListu();
this.Hide();
Form2 f2 = new Form2();
f2.ShowDialog();
}
First I am creating List from data in dgv(see here data in dgv)
then I am trying to bind listBox to this List
public Form2()
{
InitializeComponent();
Form1 f1 = new Form1();
List<Karta> nova = f1.ubaciUListu();
if(nova.Count!=0)
{
lstBox.DataSource = nova;
}
}
hope this will be helpful enough to detect issue. Thank you !
When you create a new instance of the form1, existing list will be cleared,
Form1 f1 = new Form1();
List<Karta> nova = f1.ubaciUListu();
Better way is to pass it to the 2nd form when you open it,
Form2 f2 = new Form2(Lista1);
Your form2 should be,
List<Karta> nova = new List<Karta>();
public Form2(List<Karta> input)
{
nova = input;
}
}
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)
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.
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();)
I want to hide a button when the DateTime.Now = a input date by user. The textbox100 is in the Form2 and is already public, but I know something else is missing, because I get the error: "The name 'textBox100' does not exist in the current context."
Thank you.
public void Form1_Load(object sender, EventArgs e)
{
var dateTimeStr = textBox100.Text;
var user_time = DateTime.Parse(dateTimeStr);
var time_now = DateTime.Now;
if (time_now >= user_time)
{
button1.Visible = false;
}
}
You need to improve your communication between the forms. See the accepted answer in this question.
Adapted to your code:
using ( var form = new Form2() )
{
var dateTimeStr = form.textBox100.Text;
var user_time = DateTime.Parse(dateTimeStr);
var time_now = DateTime.Now;
if (time_now >= user_time)
{
button1.Visible = false;
}
}
If you need to wait before taking the value of the TextBox, that is, wait for the user to type in the input, then you can write:
string dateTimeStr;
using ( var form = new Form2() )
{
form.submitButton.OnMouseUp += (source, e) =>
{
dateTimeStr = form.textBox100.Text;
};
}
Assuming you have a submission button somewhere in your form.
even if it's public, it still belongs to the class Form2
var dateTimeStr = Form2.textBox100.Text;
You cant get the text of textbox100 if Form2 not instantiated an having a reference in Form1. Then use the line from UnLoCo. Of course its has to be public in Form2