I am really stuck with this so I hope someone can help. I have 2 winforms, one has a listview and another has a textbox. I want to check which item is checked in the listview and copy this text into the second form. I have tried this code but it won't work, any help is greatly appreciated!
// 1st form
private void button5_Click(object sender, EventArgs e) // Brings up the second form
{
Form4 editItem = new Form4();
editItem.Show();
}
public string GetItemValue()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
return listView1.Items[i].Text;
}
}
return "Error";
}
// 2nd form
private void Form4_Load(object sender, EventArgs e)
{
Form1 main = new Form1();
textBox1.Text = main.GetItemValue();
}
You are creating a new Form1 inside of Form4 after it has been loaded. You need a reference to the original Form1. This can be accomplished in several ways, probably the easiest is passing a reference into the Form4 constructor.
// Form 1
// This button creates a new "Form4" and shows it
private void button5_Click(object sender, EventArgs e)
{
Form4 editItem = new Form4(this);
editItem.Show();
}
public string GetItemValue()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Checked == true)
{
return listView1.Items[i].Text;
}
}
return "Error";
}
--
// Form 2 (Form4)
// Private member variable / reference to a Form1
private Form1 _form;
// Form4 Constructor: Assign the passed-in "Form1" to the member "Form1"
public Form4(Form1 form)
{
this._form = form;
}
// Take the member "Form1," get the item value, and write it in the text box
private void Form4_Load(object sender, EventArgs e)
{
textBox1.Text = this._form.GetItemValue();
}
You only need a couple of changes. No need to add your own way of storing the owner form as this functionality already exists.
private void button5_Click(object sender, EventArgs e) // Brings up the second form
{
Form4 editItem = new Form4();
editItem.Show(this); //passes a reference to this form to be stored in owner
}
Then reference it on the other form.
private void Form4_Load(object sender, EventArgs e)
{
textBox1.Text = ((Form1)owner).GetItemValue();
}
Try thisway
FORM 1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Fields
public List<string> itemTexts;
public Form1()
{
InitializeComponent();
//Generate some items
for (int i = 0; i < 10; i++)
{
ListViewItem item = new ListViewItem();
item.Text = "item number #" + i;
listView1.Items.Add(item);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Checked)
{
itemTexts.Add(item.Text);
}
}
Form2 TextBoxForm = new Form2(itemTexts);
TextBoxForm.Show();
}
}
}
FORM 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
//Fields
List<string> itemTexts;
public Form2(List<string> itemTexts)
{
InitializeComponent();
this.itemTexts = itemTexts;
foreach (string text in itemTexts)
{
textBox1.Text += text + Environment.NewLine;
}
}
}
}
Related
Hey I got Code Written in Class Form1 And Form2. I want to call the method openkindForm() from Form2. I tried every soloution I found. I got this one at the moment which is not working it gives me a System.NullReferenceException. I do not know why it isnt working. I tried it so long but whatever I do it will not workout somehow. I would be thankfull for an answer.
Kind regards
First Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FBDP00
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
submenupanel.Visible = false;
}
private void funktionenSM_Click(object sender, EventArgs e)
{
switch (submenupanel.Visible)
{
case true:
submenupanel.Visible = false;
break;
case false:
submenupanel.Visible = true;
break;
}
}
public void neuepruefungSm_Click(object sender, EventArgs e)
{
submenupanel.Visible = false;
openkindForm(new Form2());
}
public Form activeForm = null;
public void openkindForm(Form childForm)
{
if (activeForm != null)
{
activeForm.Close();
}
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
backgroundPanel.Controls.Add(childForm);
childForm.Show();
}
}
}
Class 2
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static FBDP00.Form1;
namespace FBDP00
{
public partial class Form2 : Form
{
public Form1 testform;
public Form2()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void funktionenSM_Click(object sender, EventArgs e)
{
}
public void baukontrolleb_Click(object sender, EventArgs e)
{
testform.openkindForm(new Form3());
}
}
}
In Form2 you have defined a variable for Form1 (testform), but you don't set this anywhere. So this is why you get a Null reference error when you try to use it, because it is null!
So when you create your Form2 then you need to set this value. In your case, maybe in the constructor like this.
public Form1 testform;
private Form2(Form1 f1)
{
InitializeComponent();
testform = f1;
}
Then call it like this:
public void neuepruefungSm_Click(object sender, EventArgs e)
{
submenupanel.Visible = false;
openkindForm(new Form2(this));
}
However, looking at your openkindForm method, it seems to me that this really has nothing to do with Form1, and shares no variables, so should not be in this class.
You should either make this static (together with the activeForm variable), or make it a Singleton class instead. But certainly this should be a separate class.
i create a simple message box to get user input and set the result into webbrowser of previous form.
this is my MsgInput source code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public partial class MsgInput : Form
{
private readonly Main mainForm;
public string input_type;
string script;
public MsgInput()
{
this.mainForm = mainForm;
InitializeComponent();
}
private void MsgInput_Load(object sender, EventArgs e)
{
if (input_type == "echo")
{
richTextBox1.Text = "Echo : void echo ( string $arg1 [, string $... ] )";
}
}
private void btnOk_Click(object sender, EventArgs e)
{
if (input_type == "echo")
{
script = mainForm.webBrowser1.DocumentText;
if (chkNewLine.Checked == true)
{
script += "\n";
}
script += "echo " + txtInput.Text;
mainForm.webBrowser1.DocumentText = script;
this.Close();
}
}
}
and i not add anything in first form just set the webbrowser modifiers to public.
when i debug. null return when i try to submit an text
Main Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EasyPHP
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void echoToolStripMenuItem_Click(object sender, EventArgs e)
{
var msg = new MsgInput();
msg.input_type = "echo";
msg.Show();
}
private void Main_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<pre>";
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
}
}
I am assuming you are getting a null reference exception. it will be useful if you post the main form code. From what i understood, you should be passing in the main form reference and that's why you are getting a null reference.
In your code, change the constructor as below (ParentForm is whatever is the class name of your parent form)
public MsgInput(ParentForm mainForm)
{
this.mainForm = mainForm;
InitializeComponent();
}
and in the main form
MsgInput frm = new MsgInput(this);
frm.input_type = "echo";
frm.Show(this);
Else please share the full code and we can quickly help
I am using a listBox to play file from media player on my form, I am using the code below to get files in my listbox,as it retuns the file name, now I am able to play files from listBox and now I want next item in the listbox to be played automatically after a time gap.How to do this
this.listBox1.DisplayMember = "Name";/*to display name on listbox*/
this.listBox1.ValueMember = "FullName";/*to fetch item value on listbox*/
listBox1.DataSource = GetFolder("..\\video\\"); /*gets folder path*/
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder)
.GetFiles("*.mpg",SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
for listbox I am using the following code
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem);
}
for listBox1 I am using the code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e )
{
StreamWriter sw = new StreamWriter("..\\Debug\\List.txt", true);
//Player.URL = Convert.ToString(listBox1.SelectedItem);
string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
//listView1.Items.Add(listBox1.SelectedItem.ToString());
foreach (object o in listBox1.SelectedItems)
sw.WriteLine(DateTime.Now + " - " + o);
sw.Close();
}
Then I am using a button to transfer selected listbox1 files to listBox2 on another form
private void button1_Click_1(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object item in listBox1.Items)
{
sb.Append(item.ToString());
sb.Append(" ");
}
string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
//listBox2.Items.Add(listBox1.SelectedItem.ToString());
Form3 frm = new Form3();
foreach (int i in listBox1.SelectedIndices)
{
frm.listBox2.Items.Add(listBox1.Items[i].ToString());
frm.Show();
this.Hide();
}
}
listbox2 code is mentioned above.
You have to intercept the PlayStateChange of the player. Once you get the int value 8, which is MediaEnded, you can play the next video in the list after the desired time gap.
[UPDATE] - this does not work for .NET 2.0, so get the proper version for Form3.cs from the [EDIT] at the end of the answer
Here's Form3.cs (.NET 4.5):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMPLib;
namespace WindowsFormsApplication10
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
this.listBox2.DisplayMember = "Name";/*to display name on listbox*/
this.listBox2.ValueMember = "FullName";/*to fetch item value on listbox*/
Player.PlayStateChange += Player_PlayStateChange;
}
async void Player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
if (listBox2.SelectedIndex + 1 < listBox2.Items.Count)
{
await System.Threading.Tasks.Task.Delay(3000);
listBox2.SelectedItem = listBox2.Items[listBox2.SelectedIndex + 1];
}
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem.GetType().GetProperty("FullName").GetValue(listBox2.SelectedItem)).ToString();
Player.Ctlcontrols.play();
}
}
}
And here's Form1.cs (.NET 4.5):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
//using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.listBox1.DisplayMember = "Name";/*to display name on listbox*/
this.listBox1.ValueMember = "FullName";/*to fetch item value on listbox*/
listBox1.DataSource = GetFolder("..\\video\\"); /*gets folder path*/
}
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder)
.GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
private void button1_Click(object sender, EventArgs e)
{
Form3 frm = new Form3();
frm.FormClosed += frm_FormClosed;
foreach (int i in listBox1.SelectedIndices)
{
frm.listBox2.Items.Add(new
{
Name = ((FileInfo)listBox1.Items[i]).Name,
FullName = ((FileInfo)listBox1.Items[i]).FullName
});
frm.Show();
this.Hide();
}
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
this.Show();
}
}
}
[EDIT] - this should work for .NET 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WMPLib;
namespace WindowsFormsApplication10
{
public partial class Form3 : Form
{
System.Timers.Timer _timer = new System.Timers.Timer();
object _locker = new object();
public Form3()
{
InitializeComponent();
this.listBox2.DisplayMember = "Name";/*to display name on listbox*/
this.listBox2.ValueMember = "FullName";/*to fetch item value on listbox*/
Player.PlayStateChange += Player_PlayStateChange;
_timer.Elapsed += _timer_Elapsed;
_timer.Interval = 3000;
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
lock (_locker)
{
this.Invoke((MethodInvoker)delegate
{
if (listBox2.SelectedIndex + 1 < listBox2.Items.Count)
{
listBox2.SelectedItem = listBox2.Items[listBox2.SelectedIndex + 1];
}
});
}
}
void Player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
_timer.Start();
}
else if ((WMPLib.WMPPlayState)e.newState == WMPLib.WMPPlayState.wmppsReady)
{
Player.Ctlcontrols.play();
}
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Player.URL = Convert.ToString(listBox2.SelectedItem.GetType().GetProperty("FullName").GetValue(listBox2.SelectedItem, null)).ToString();
}
}
}
i need your help.
I have two forms, Form1 and Form2. In Form1 i have a checkBox1 and in Form2 I have a checkBox2. All i want is the value of checkBox1 tranfering automatically in checkBox2.
Thanks in advance
First of all, in a multi-form application, form-form direct contact should not be permitted. However, I can think of a way which I present here considering yours is an exceptional scenario. So the method might violate usual best practices.
Here is the method
Make your checkboxes in your forms as Public. You can do that by clicking on the CheckBox in the design mode and then selecting Public under Modifiers in Properties window. This step makes your checkbox accessible from outside your form's instance.
Write the following code in CheckedChanged event of CheckBox in Form1.
((Form2)(Application.openForms["Form2"])).checkBox1.Checked = this.checkBox1.Checked;
However, I strongly recommend revisiting your strategy based on your application need.
On Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Form2 a = new Form2();
a.c = checkBox1.Checked;
a.ShowDialog();
}
}
On Form2:
public partial class Form2 : Form
{
public bool c;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
checkBox1.Checked = c;
}
}
All instances of Form2 within an MDI parent will reflect any change to the CustomCheckBox control Checked property placed on the Form. Of course, this would be true of when placing the CustomCheckBox on any MDI child form, just set up the proper events like Form2.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
CustomCheckBox.CheckChanged += (object sender, EventArgs e) => {
if (sender != m_customCheckBox) { m_customCheckBox.Checked = CustomCheckBox.GetCheck(); }
};
FormClosed += (object _sender, FormClosedEventArgs _e) => {
CustomCheckBox.CheckChanged -= (object __sender, EventArgs __e) => { };
};
}
};
};
////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public class CustomCheckBox : CheckBox {
static private bool? m_checked = null;
static private object m_synchRoot = new object();
static public event EventHandler CheckChanged;
public CustomCheckBox() {
if (HasCheckValue) {
// Do this BEFORE we set up the CheckChanged event so that
// we do not needlessly kick off the CustomCheckBox.CheckChanged
// event for any other existing CustomCheckBoxes (as they already
// have their Checked property properly set)...
Checked = CustomCheckBox.GetCheck();
}
this.CheckedChanged += new EventHandler(OnCheckedChanged);
}
protected void OnCheckedChanged(object sender, EventArgs e) {
if (CustomCheckBox.HasCheckValue && this.Checked == CustomCheckBox.GetCheck()) {
return;
} else {
CustomCheckBox.SetCheck(this.Checked);
if (CustomCheckBox.CheckChanged != null) {
CustomCheckBox.CheckChanged(sender, e);
}
}
}
static public bool HasCheckValue {
get {
lock (m_synchRoot) {
return m_checked.HasValue;
}
}
}
static public bool GetCheck() {
lock (m_synchRoot) {
return m_checked.Value;
}
}
static private void SetCheck(bool _check) {
lock (m_synchRoot) {
m_checked = _check;
}
}
};
};
I have a windows form with a DropDownList with a fixed number of items. How do I make the DropDownList increment to the next item when I press Enter and when it reaches the end of the items, return to the first item.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.DataSource = CreateItems();
}
private List<string> CreateItems()
{
List<string> lst = new List<string>();
lst.Add("One");
lst.Add("Two");
lst.Add("Three");
lst.Add("Four");
return lst;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
if (comboBox1.SelectedIndex == comboBox1.Items.Count-1)
{
comboBox1.SelectedIndex = 0;
return;
}
if (comboBox1.SelectedIndex >=0 & comboBox1.SelectedIndex< comboBox1.Items.Count-1)
{
comboBox1.SelectedIndex = comboBox1.SelectedIndex+1;
}
}
}
}
}
You need to handle the KeyDown event and change the SelectedIndex property.