I want to get some data to fill a listview control, but this data it's determined in other form. This is what I code in form1 (Nuevo_Credito):
private void combo_cliente_SelectionChangeCommitted(object sender, EventArgs e)
{
Credito_Grupo ventana = new Credito_Grupo(combo_cliente.SelectedItem);
ventana.ShowDialog();
}
public void AgregaIntegrantes(string id, string nombre, string monto)
{
ListViewItem elem = new ListViewItem(id);
elem.SubItems.Add(nombre);
elem.SubItems.Add(monto);
listView_integrantes.Items.Add(elem);
}
I'm invoking form2 (Credito_grupo) as show dialog window, then I want to retrieve some values and pass them to Form1 using the public method "AgregaIntegrantes". So in form2 I did the following:
public Credito_Grupo(dynamic item)
{
this.id = item.IDCliente;
this.nombre = item.NomComp;
InitializeComponent();
}
private void Credito_Grupo_Load(object sender, EventArgs e)
{
text_nombre.Text = this.nombre;
}
private void button_AgregaCliente_Click(object sender, EventArgs e)
{
Nuevo_Credito obj = new Nuevo_Credito();
obj.AgregaIntegrantes(id.ToString(), nombre, text_monto.Text);
this.Close();
}
When the event button_AgregaCliente_click is triggered I need to add the data to listview in form1 using the method described above, but none data is added. I found a solution using delegates here 3077677, is there an approach using objects?
You have an error in button_AgregaCliente_Click method (the last one in the listing). You create a new Nuevo_Credito form there, and pass the data to listview. It looks OK. But this newly created Nuevo_Credito form does exist only in the local variable, so then you throw it away without displaying it when button_AgregaCliente_Click finishes.
I think you need to delete this line: Nuevo_Credito obj = new Nuevo_Credito();
You need to get your real Nuevo_Credito form, not create a new one here.
You can send this from your Nuevo_Credito to the constructor of the Credito_Grupo form. Then you can use it to call back to the original Nuevo_Credito. This approach is based only on objects, and not delegates. As you wanted. :-)
Related
I have file manager program that displays folder in a treeView on the left hand side of a form (frmMain) and files in listView on the left side. I want to be able to select a file (item) from the listView then display the file name in a text on another form with the label = 'Enter a file name.' then rename the file with that new name.
Code from the second form.
public frmRename(string oFile)
{
InitializeComponent();
textBox1.Text = oFile;
}
private void bntOK_Click(object sender, EventArgs e)
{
string nFileName;
nFileName = textBox1.Text;
frmMain fm = new frmMain();
fm.re_nameFile(nFileName);
}
This code runs without any errors; however, when uncommented that is presently commented I get error 'Value of zero is not a valid for index'. I know that this error has talked about a lot; however, I am concern with a different aspect of this error. If I use a line of in private function I don't get this error; whereas, if I use it public function I do. First of all I want to understand why this happens? Second can you tell me how to fix the problem?
So in frmMain you create a new frmRename and in frmRename you create a new frmMain. Bad idea. The new frmMain knows nothing about the original frmMain (including its populated listView).
Solution: in frmMain.bntRename_Click call
rename.ShowDialog();
newFileName = rename.nFileName;
do whatever you want to do with the new name and in frmRename define
public string nFileName {get; private set;}
and further change
private void bntOK_Click(object sender, EventArgs e)
{
nFileName = textBox1.Text;
Close();
}
I have two forms that need to interact with each other. The parent form has 4 fields and an add button that saves data from each field to an instance of a class object. After its saved to an object the object is stored in a listbox, which the child form contains. I created a custom event to handle that stuff, but I am surely doing something wrong.
What's supposed to happen is that when both windows are open, and there is data in the listbox, whatever item that is selected from the child form listbox fills the parent form fields with the data from that object. When I test out my code, only the first item has the data properly filling the correct fields. If I click any other item after the first selection, the main form fields do not update at all.
Specific to my issue the child form has the following codes:
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
PotionForm tempMain = new PotionForm(); //this was a test, nothing changed
pPotionList.SelectionMode = SelectionMode.One;
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(this, new EventArgs());
}
tempMain.Refresh(); // this too
}
The parent form has these codes
private void pListDisplay_Click(object sender, EventArgs e)
{
PotionList secForm = new PotionList();
secForm.secFormBox.DataSource = potionBindList;
PotionListChanged += secForm.HandlePotionListChanged;
secForm.ChildPotionListChanged += HandleChildPotionListChanged;
secForm.ListBoxItemClicked += HandleListBoxItemClicked; //this line
secForm.Show();
}
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
pTypeInput.SelectedItem = aPotion._type;
pMagInput.Value = aPotion._magnitude;
pNameInput.Text = aPotion._name;
pBonusInput.Checked = aPotion._bonus;
}
I am currently using Visual Studio Community 2015 if that's relevant.
Ok after seeing all the necessary code I would say that the problem is that you never pass the values from the Child-Form to the Parent. Whenever the event HandleListBoxItemClicked is fired only the initial values of aPotion are written to the controls.
As a solution I would suggest to pass the SelectedItem as the sender when you fire the ListBoxItemClicked event in the childform:
CHILD
public EventHandler ListBoxItemClicked;
private void pPotionList_SelectedIndexChanged(object sender, EventArgs e)
{
Potion p = pPotionList.SelectedItem as Potion;
pPotionList.SelectionMode = SelectionMode.One;
if (p != null)
{
if (ListBoxItemClicked != null)
{
ListBoxItemClicked(p, new EventArgs());
}
}
}
Not you can use this information in the parent form and disperse the information as you please:
PARENT
public void HandleListBoxItemClicked(object sender, EventArgs e)
{
Potion p_parent = sender as Potion;
if(p_parent != null)
{
pTypeInput.SelectedItem = p_parent._type;
pMagInput.Value = p_parent._magnitude;
pNameInput.Text = p_parent._name;
pBonusInput.Checked = p_parent._bonus;
}
}
No refresh or anything else should now be necessary. Hope it helps
I am struggling to pass data between two forms (all I want to do is have a textbox in Form1, and show that textbox value in textbox1, which is located in Form2). How would I go about this, using WPF? Have looked at quite a few solutions, but cannot seem to get any of them at all to work.
For the form in which I'm wanting to display the values (in tbd.Text), here is the code:
namespace test
{
/// <summary>
/// Interaction logic for OptionDisplayWindow.xaml
/// </summary>
public partial class OptionDisplayWindow : Window
{
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = "k"; //want to change this value based on "s" in the other form
}
The form in which the text is transferred from (want to display the string):
public void Button1_Click(object sender, RoutedEventArgs e)
{
string s = "testText"
}
I have tried every single other answer on SO (spent the past 6 hours trying) and have had absolutely no luck.
EDIT 2: Using the method listed as the best answer here Send values from one form to another form I've come up with this code for Form1:
private void ttbtn_Click(object sender, RoutedEventArgs e)
{
using (Form2 form2 = new Form2())
{
tbd.Text = form2.TheValue;
}
}
And the code for Form2:
public string TheValue
{
get { return arrayTest.Text; }
}
However, I'm getting the error 'Form 2': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
The code that you put in the sample project (that you provided as a link in the comments) should be in your question. Given that it becomes much easier to understand what you're trying to do and to give you a workable solution.
I would suggest creating a "DataTransferObject" and pass that between each form.
public class Dto
{
public string Text;
}
The code in MainWindow would then look like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dto = new Dto();
window2 win2 = new window2();
win2.Dto = dto;
win2.ShowDialog();
textBox1.Text = dto.Text;
}
And the code in window2 would look like this:
public Dto Dto;
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (this.Dto != null)
{
this.Dto.Text = textBox2.Text;
}
}
That is one way - out of about a million - of transferring data between forms. An advantage of using a data transfer object is that it begins you on the road of separating your data from your UI, and that is generally a very good thing to do.
Another simple way to pass data between forms is using your application's settings.
Step 1: Create a setting, open the "Project" menu and pick "test Properties..."
this will take you to the settings page, create a setting name it however you want, I named mine "PassString" and make sure it's a string type and the Scope is set to user.
Step 2. Lets set the string setting to your textbox.text property, add these changes to the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.PassString = textBox1.Text;
window2 win2 = new window2();
win2.ShowDialog();
}
Step 3. Update the text on your second window Initialization Process.
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = Properties.Settings.Default.PassString;
}
P.S. you may have to add a reference to reach your application settings.
using test.Properties;
I have two Windows Forms. I have read data from the database and load data into Listbox1 on Form1(FrmSelection). Now what i want is, when a user select a value from Listbox1 on Form1 and click process button, the selected value must be loaded on Form2(FrmProcessOrder) Listbox2. I have tried different examples but am not get it to work. here are the steps below
1.Run Application
2.FrmSelection Opens with empty listbox,then click process button which opens FrmSelection
3.FrmSelections opens up,this form contains one listbox and data the i have read from the database.
4.Select one item from the listbox
5.Click Addforms button after selecting the item from listbox on FrmSelections.
Selected item must appear on FrmProcessorder listbox.
Problem - Am getting error on FrmProcessorder form when i click Addforms button after selecting the item(object not set to an instance of an object)
here is my code below..
Form1(FrmSelection)
public partial class FrmProcessOrder : Form
{
public FrmProcessOrder()
{
InitializeComponent();
}
private void btnProcess_Click(object sender, EventArgs e)
{
Program._FrmSelection = new FrmSelection();
Program._FrmSelection.Show();
}
public void AddList(ListBox _Listing)
{
ListBoxForms.Items.AddRange(_Listing.Items);
}
}
Form 2(FrmProcessOrder )
FrmProcessOrder _FrmProcessOrder;
public FrmSelection()
{
InitializeComponent();
LoadData();
}
//Method which reads data from the db and laod data on listview
public void LoadData()
{
_connection = "Data Source=MILESTONE-PC;Initial Catalog=Jack;Integrated Security=True";
_sql = "Select * from tblJackon";
_conn = new SqlConnection(_connection);
_conn.Open();
_comm = new SqlCommand(_sql, _conn);
_adapt.SelectCommand = _comm;
_adapt.Fill(_dataset, _sql);
DataTable _tbl = _dataset.Tables[0];
_dtrow = null;
foreach (DataRow _dataVariable in _tbl.Rows)
{
_dtrow = _dataVariable;
ListBoxSelection.Items.Add((_dtrow["FormNames"]));
}
}
private void btnAddForms_Click(object sender, EventArgs e)
{
_FrmProcessOrder.AddList(ListBoxSelection); // It throws error on this line after select from listbox so that the item must to FrmProcessOrder listbox
_FrmProcessOrder = new FrmProcessOrder();
}
Edit (after the question is edited):
Check this:
FrmProcessOrder _FrmProcessOrder; //no object declared
private void btnAddForms_Click(object sender, EventArgs e)
{
_FrmProcessOrder.AddList(ListBoxSelection); // This is null exception
_FrmProcessOrder = new FrmProcessOrder(); //it should not be put here
}
Your _FrmProcessOrder is used before it is initialized properly. Do this instead:
FrmProcessOrder _FrmProcessOrder = new FrmProcessOrder(); //Now it is declared, only once
private void btnAddForms_Click(object sender, EventArgs e)
{
_FrmProcessOrder.AddList(ListBoxSelection); // Now it should be ok
}
Original:
One of the simplest way would be to put your input as a field (or create a method call to do it) rather than as a constructor argument.
Change this:
public FrmProcessOrder(ListBox _List)
{
InitializeComponent();
ListBoxForms2.Items.AddRange(_List.Items);
}
Into this
public FrmProcessOrder()
{
InitializeComponent();
}
public void AddList(ListBox _List){
ListBoxForms2.Items.AddRange(_List.Items);
}
Then when you could call your Form Method whenever you need
_FrmProcessOrder.AddList(listBox);
I believe you have wrongly copied the code blocks(swapped Form2 & Form1).
This line Application.Run(new FrmProcessOrder()); should be replaced by Application.Run(new FrmSelection()); which would load the data from the database.
The compilation error you are seeing is since you do not have an empty constructor. As per the current code, to instantiate 'FrmProcessOrder' you have to provide an instance of ListBox.
In this line
Application.Run(new FrmProcessOrder());
you're trying to instantiate a new FrmProcessOrder, but you have one constructor like this:
public FrmProcessOrder(ListBox _List)
so you can't instantiate without a parameter ListBox.
If you want this you have to add to Form1 the empty constructor:
public FrmProcessOrder()
{
}
I am trying to write a simple form application with mono Gtk# but am already stuck in the beginning I create a Dialog form inherits from Gtk.Dialog. The dialog form for collection basic information and returning these information as an object to main window or trigger some event to main window so it can do what it suppose to do in this case bind the data a TreeView control (which is another story). These are what I have tried so far;
Dialog code
public partial class MyDialog : Gtk.Dialog
{
public MyDialog ()
{
this.Build ();
}
protected void OnButtonOkClicked (object sender, EventArgs e)
{
int portNumber = 0;
iint.TryParse (spnPort.Text, out portNumber);
var myObj = new MyObj ();
myObj.Username = txtUsername.Text;
myObj.Password = txtPassport.Text;
// did not work as ParentWindow is a Gdk.Window
//(this.ParentWindow as MainWindow).AddObj(myObj);
//Also did not work because there is no response related method
//or property in the Dialog please read below code block this will make more sense
//this.OnResponse(myObj);
}
}
MainWindow Code to call dialo
protected void OnAddActionActivated (object sender, EventArgs e)
{
MyDialog s = new MyDialog();
s.Run();
s.Response += HandleResponse;
}
void HandleResponse (object o, ResponseArgs args)
{
//as this event has args.Args and args.RetVal I thought one would do what I wanted
//maybe I am using them all wrong
}
I appreciate it if some one can explain what is Gdk.Window is and what it is doing under Gtk control.
Just store the object you want to return in your dialog object, and provide access to it using a property. Don't forget to check whether the user pressed the cancel button (if you have one), conveniently by examining the return value of Run().
For an example see the sample code for the stock FileChooserDialog in the official documentation.