Can't add ListViewItem in function - c#

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();

Related

Passing subform textbox value back to main form

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.

c# passing values through constructor but are not displayed in a textbox

i have passes some values though a constructor from one from to another. the values are successfully transferred in another form through constructor but when i display them in a textbox the values become null and the textbox remains empty. i am showing the code of the constructor for both forms.
starting form which opens another form
private void lbl_imgpass_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string img = img_name.Text;
Setimgpass st = new Setimgpass(img);
st.Show();
}
form1(from where the values are transferred to another form)
else
{
first = textBox2.Text;
second = textBox3.Text;
third = textBox4.Text;
Adduser add = new Adduser(x1low, x1up, x2low, x2up, x3low, x3up, y1low, y1up, y2low, y2up, y3low, y3up, first, second, third);
this.Hide();
}
second form(where the values are received)
public Adduser(string x1low, string x1up, string x2low, string x2up, string x3low, string x3up, string y1low, string y1up, string y2low, string y2up, string y3low, string y3up,string first, string second, string third)
{
InitializeComponent();
frst = first;
secnd = second;
thrd = third;
lowx1 = x1low;
upx1 = x1up;
lowx2 = x2low;
upx2 = x2up;
lowx3 = x3low;
upx3 = x3up;
lowy1 = y1low;
upy1 = y1up;
lowy2 = y2low;
upy2 = y2up;
lowy3 = y3low;
upy3 = y3up;
txt_imgpass.Text = frst + " " + secnd + " " + thrd;
}
txt_imgpass is the textbox in which i want values.
In the first form the values are passed to the object "add" that you created .
You can simply use static variables to pass data from one form to another .
EDIT
You might as well want to try something like this instead of static variables
Form 1 :
assuming this is the button you click on to show the second form
private void button1_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBox1.Text);
form.Show();
}
in Form 2 you can do something like this
public Form2(string text)
{
InitializeComponent();
label1.Text = text;
}

How do I pass variables stored in Properties into another windows form?

So I need to be able to pass a property(name) into another windows form.
In the first form, the user is prompted to key in their name, while in the second one, their name is shown.
My problem is that although the value keyed in in the first form is saved (I have a Message box to show me) when the new form runs, the value of the property is reset to the placeholder name from the constructor class. Here are the codes(Form1 being the second form)
Both of them have initialised the reference to the contructor class at the start.
else if (select > 0 || txtName.Text != "")
{
p.Name = txtName.Text; // Save Name as property
MessageBox.Show("" + p.Name);
this.Hide();
Form1 form = new Form1();
form.ShowDialog();
}
For Form1:
private void Form1_Load(object sender, EventArgs e)
{
setName();
MessageBox.Show("" + p.Name);
timer1.Start();
label3.Text = "Player: " + p.Name;
}
Create a property in Form1 to accept the name:
public class Form1 : Form
{
//other stuff
public string Name {get;set;}
}
Then set that property when creating the form:
else if (select > 0 || txtName.Text != "")
{
this.Hide();
Form1 form = new Form1();
form.Name = txtName.Text;
form.ShowDialog();
}

public variables using in the second form

I have a "simple" problem with assign variables from FORM1 (in my code Form1) and using those variables in FORM2 (in my code frLeczenie). So I started to create a public string variables:
public string wynikImie;
public string wynikUmaszczenie;
public string wynikDataUrodzenia;
public string wynikPlec;
public string wynikZnakiSzczegolne;
public string wynikCzyWykastrowane;
To those variables I'll assign data from SQL Database:
private void dgZwierze_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string zapytanie = "SELECT IMIE_ZWIERZECIA, DATA_URODZENIA, PLEC, ZNAKI_SZCZEGOLNE, UMASZCZENIE, CZY_WYKASTROWANE FROM tbZwierze WHERE tbZwierze.IMIE_ZWIERZECIA = '" + wynikImie + "' AND tbZwierze.UMASZCZENIE = '" + wynikUmaszczenie + "'";
SqlCommand cmdZapytanie = new SqlCommand(zapytanie, cs);
cs.Open();
SqlDataReader reader = cmdZapytanie.ExecuteReader();
if (reader.Read())
{
wynikImie = reader.GetValue(0).ToString();
wynikDataUrodzenia = reader.GetValue(1).ToString();
wynikPlec = reader.GetValue(2).ToString();
wynikZnakiSzczegolne = reader.GetValue(3).ToString();
wynikUmaszczenie = reader.GetValue(4).ToString();
wynikCzyWykastrowane = reader.GetValue(5).ToString();
}
cs.Close();
}
To this moment all is great, but problem occurs when I opened the FORM2:
private void btnLeczenie_Click(object sender, EventArgs e)
{
frLeczenie leczenie = new frLeczenie();
leczenie.ShowDialog();
}
Suddenly my all data assigned to public string variables is missing, and I can't using their in the FORM 2:
private void frLeczenie_Load(object sender, EventArgs e)
{
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
textBox2.Text = formaglowna.wynikDataUrodzenia;
textBox3.Text = formaglowna.wynikPlec;
textBox4.Text = formaglowna.wynikZnakiSzczegolne;
textBox5.Text = formaglowna.wynikUmaszczenie;
textBox6.Text = formaglowna.wynikCzyWykastrowane;
}
What I'm doing wrong? Maybe I missing something? Could you take a look on this?
Regards,
Peter.
new Form1(); creates a new instance of your first form, but you want to use the already initialized form with it's variables instead. So you could pass the form instance via constructor to your second form and store it in a property:
in first form:
frLeczenie leczenie = new frLeczenie(this);
second form constructor:
public frLeczenie(Form1 formaglowna)
{
InitializeComponent();
this.Formaglowna = formaglowna;
// ...
}
public Form1 Formaglowna{ get; set; }
Now you access them via property:
textBox1.Text = Formaglowna.wynikImie;
// ...
Note that you set the values in an instance of the form in it's dgZwierze_CellContentClick method. However in form 2 you are creating a new Form1 that has never been shown or had that method called. So the values are empty.
Form1 formaglowna = new Form1();
textBox1.Text = formaglowna.wynikImie;
What you need is to pass the real form1 into form2 and not create a new form 1
When you create the new form1 in the last part of your code, it is a new blank instance of the class. Each instance of a class or form will have its own variable values. If you really need these variables to be available and shared on all objects of a given class, make them static.

Getting checkbox tags (in a panel) to new form

Rather new to C# so please forgive me if i am missing something simple or am trying to just do this the wrong way.
I am creating another form to compliment my main form and it needs to pull some of the information from Main form on button click of Second form. The information on the Main for is stored in checkboxes and textboxes.
I have the textboxes working fine but cannot figure out how to pull the checkboxes tag data over along with the formatting. Main Form is working fine as is except I cannot figure out how to bring the checkbox data over as well.
This is the code i currently use to display the checkbox TAG data on my main form.
//Statements to write checkboxes to stringbuilder
string checkBoxesLine = "\u2022 LIGHTS ";
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is string)
{
string checkBoxId = (string)checkBox.Tag;
checkBoxesLine += string.Format("{0}, ", checkBoxId);
}
}
}
This is the button i am using to open the new form and move the checkbox tag data and textbox.text data to the new form.
private void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
cust_modem = cust_modem_text.Text;
//Opens CODE BLUE form and pushes text to it.
code_blue_form CBForm = new code_blue_form();
CBForm.cust_name_cb = cust_name_text.Text;
CBForm.cust_cbr_cb = cust_callback_text.Text;
CBForm.cust_wtn_cb = cust_btn_text.Text;
CBForm.cust_notes_cb = cust_modem + "\r\n" + trouble_shooting + "\r\n" + services_offered + "\r\n" + other_notes;
CBForm.Show();
}
Here is my code for the Second form and how i am getting the information to populate textboxes on that form.
public partial class code_blue_form : Form
{
public string cust_name_cb;
public string cust_wtn_cb;
public string cust_cbr_cb;
public string cust_notes_cb;
public string cust_modem_cb;
public code_blue_form()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
}
}
}
Please forgive the long post! Any ideas/direction on this would be greatly appreciated. Thanks!
I am not going to answer straight away using ur code. I find code smell. If I were you I would do this (but then if you are adamant about going with the same design, then you can tweak my code accordingly, no big deal, the bottom line is you get the idea how to do):
void code_blue_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var checkBoxIds = GetCheckBoxIds();
cust_modem = cust_modem_text.Text;
trouble_shooting = tshooting_text.Text;
services_offered = services_offered_text.Text;
other_notes = other_notes_text.Text;
//take off underscore convetion and replace with camelCase convention.
CodeBlueForm cbForm = new CodeBlueForm(checkBoxIds, cust_name_text.Text,
cust_callback_text.Text,
cust_btn_text.Text,
cust_modem + "\r\n" +
trouble_shooting + "\r\n" +
services_offered + "\r\n" +
other_notes);
cbForm.Show();
}
private List<int> GetCheckBoxIds()//even better naming required like GetFruitIds()
{ //(whatever the id is of) or even better Tag
//checkBoxes with the Fruit object iself and not ids.
List<int> checkBoxIds = new List<int>(); //So you can call GetFruits();
foreach (Control control in pnlCheckBoxes.Controls)
{
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
if (checkBox.Checked && checkBox.Tag is int) //tag them as ints.
checkBoxIds.Add((int)checkBox.Tag); //I hope ids are integers.
}
}
return checkBoxIds;
}
public partial class CodeBlueForm : Form
{
List<int> checkBoxIds = new List<int>():
string cust_cbr_cb; //should be private.
string cust_name_cb;
string cust_wtn_cb;
string cust_notes_cb;
string cust_modem_cb;
public CodeBlueForm(List<int> ids, string cust_name_cb, string cust_wtn_cb,
string cust_notes_cb, string cust_modem_cb)
{
InitializeComponent();
this.checkBoxIds = ids;
this.cust_name_cb = cust_name_cb;
this.cust_wtn_cb = cust_wtn_cb;
this.cust_notes_cb = cust_notes_cb;
this.cust_modem_cb = cust_modem_cb;
}
private void button1_Click(object sender, EventArgs e)
{
cb_name_text.Text = cust_name_cb;
cb_wtn_text.Text = cust_wtn_cb;
cb_cbr_text.Text = cust_cbr_cb;
cb_notes_text.Text = cust_notes_cb;
string checkBoxesLine = "\u2022 LIGHTS ";
// if you dont require a lot of string formatting, then just:
checkBoxesLine += string.Join(", ", checkBoxIds);
// or go with your classical:
//foreach (int id in checkBoxIds)
// checkBoxesLine += string.Format("{0}, ", checkBoxIds);
//and do what u want with checkboxline here.
}
}

Categories