Beginner here.
I have a list on my MainPage that I am adding items to by typing stuff into a textbox submitting it. After creating a listview item, I would like to be able to click on an item and see its value in another page.
I created a DetailsPage for this, but I don't know what the best way is to share that data across these pages.
This is what I have in my MainPage so far:
public sealed partial class MainPage : Page
{
public int itemCounter;
public MainPage()
{
this.InitializeComponent();
//This is the button that submits the entered text
public void btnSubmitInPopup_Click_1(object sender, RoutedEventArgs e)
{
//Create new listview item and textblock
ListViewItem item = new ListViewItem();
TextBlock txtBloodSugarValue = new TextBlock();
//Save text input value to label and add item to list
txtBloodSugarValue.Text = txtInput.Text;
item.Content = txtBloodSugarValue;
mainListView.Items.Add(item);
//Reset text input field
txtInput.Text = "";
//Update counter of items in list
itemCounter = mainListView.Items.Count();
lblItemCounter.Text = itemCounter.ToString();
}
}
My DetailPage literally has just one label that I am trying to populate with whatever value is in the listview item that I clicked on in my MainPage.
What's the best way to do this?
Hope this makes sense.
Thanks so much.
You have 3 way to do that:
declaring static variable and set that in first form and use in second form(or anywhere!)
Create public field/propeey inside second form class and set it from first form
Pass value as parameter to constructor/function of second class
I add second form class here:
public static int StaticVariable { get; set; }//First Method
public int PublicProperty { get; set; }
public Form2(int Value)
{
InitializeComponent();
//Do your code here with constructor way here
}
public Form2()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//Do your code for 1,2 here
}
public void SetValueWithFunction(int value)
{
//Do your code for setting value with second type in Number 3
}
I hope this helps :)
Related
Hi I want to move listbox items to datagridview but I'm getting error can you see where I'm going wrong?
I got 2 form,1 datagridview,2 button ,1 listbox and 1 class ( For moving )
form1, got 2 items ( datagridview and 1 button( to open form 2 ))
form2, got 2 item ( listbox and 1 button( to move items datagridview rows )) I think I've created in your mind what I want to do so far, let me add pictures about application too
Picture 1 ( Form1 )
Picture 2 ( Form2 )
In class I added the functions for the buttons ( Shows in picture2 ( Button Load (Is ok) |Button Clear (Is ok) |Button Import (where I'm getting error))
well I have one solution for Import button (Below are the form 1 codes you can check)
public static Form1 instance;
public DataGridView dgv1;
public Form1()
{
InitializeComponent();
instance = this;
dgv1 = dataGridView1;
}
Below are the codes of form2 for the solution
private void btnImport_Click_1(object sender, EventArgs e)
{
foreach (var item in listBox1.Items)
{
int Import = Form1.instance.dgv1.Rows.Add();
Form1.instance.dgv1.Rows[Import].Cells["Email"].Value = item;
this.Close();
}
}
These codes solve my current problem, but it's very confusing when I want to do it for more than one object, so I want to call my operations by creating a method in class, but I get an error doing so
let me share codes for class
using System.Windows.Forms;
namespace Sndr01
{
internal class Class1
{
public string import (ListBox lst , DataGridView dgv)
{
childListForm frm = new childListForm();
string done = lst.ToString();
foreach (var item in lst.Items)
{
int imp = dgv.Rows.Add();
dgv.Rows[imp].Cells["Email Address"].Value = item.ToString();
frm.Close();
}
return done;
}
here is the my form1 codes
public partial class ListForm : Form
{
public DataGridView dgvv;
public ListForm()
{
InitializeComponent();
DataGridViewSettings(dgv1);
dgv1.DataSource = dgvv;
}
}
here is the my form2 codes
public partial class childListForm : Form
{
ListForm lf = new ListForm();
DataGridView dgvx;
public childListForm()
{
InitializeComponent();
dgvx.DataSource = lf.dgvv.DataSource;
}
private void kryptonbtnImport_Click(object sender, EventArgs e)
{
Class1 c1 = new Class1();
c1.import(lstLeadsbox,dgvx);
}
}
where I'm doing wrong? I'm so confused I would be very grateful if you could help
I may have told you a little too much and bored you, but I wanted to specify the details and not leave any question marks in your mind
Thanks
Rather than passing controls between forms a better way is to have an event to pass data from child to parent form.
In this generic example the ListBox is populated with month names. An event is used to pass data to the parent form where the parent form subscribes to the child form event.
Child form code
public partial class ChildForm : Form
{
public delegate void OnPassMonths(string text);
public event OnPassMonths PassMonths;
public ChildForm()
{
InitializeComponent();
listBox1.DataSource = System.Globalization
.DateTimeFormatInfo.CurrentInfo
.MonthNames.Take(12)
.ToList();
}
private void PassDataButton_Click(object sender, EventArgs e)
{
foreach (var monthName in (List<string>)listBox1.DataSource)
{
PassMonths?.Invoke(monthName);
}
}
}
In the main form, month names are added only if non-existing using the following extension method to keep code in the form clean and easy to read.
public static class DataGridViewExtensions
{
// in this case the cell is assumed to be 0, change if not 0
public static bool MonthNotExists(this DataGridView dgv, string month) =>
dgv.Rows.Cast<DataGridViewRow>()
.FirstOrDefault(row => row.Cells[0].Value.ToString()
.Equals(month)) == null;
}
Main form code
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void ShowChildForm_Click(object sender, EventArgs e)
{
ChildForm childForm = new ChildForm();
childForm.PassMonths += OnPassMonths;
try
{
childForm.ShowDialog();
}
finally
{
childForm.Dispose();
}
}
private void OnPassMonths(string month)
{
if (dataGridView1.MonthNotExists(month))
{
dataGridView1.Rows.Add(month);
}
}
}
I have list, listbox, button and a textbox.
My idea is to make that by clicking on the button, the content of the textbox is added to the list, and then pass the data to a listbox.
My problem is, if you add what I write, but the items that are in the listbox are overwritten by the new one that you insert. and I want only more items added. to the list and to go to the listbox. Thank you very much for your answers. This is the code of my button:
private void button54_Click(object sender, RoutedEventArgs e)
{
List<Playlists> List1 = new List<Playlists>();
List1.Add(new Playlists(textBox3.Text, #rutaalbum));
lbListbox.ItemsSource = List1;
}
I am just making a demo stand in for your Playlists class.
ToString has been overridden in order to display some text in the listbox. Without it, you will only display the class name.
ObservableCollection is used instead of List, so that the listbox updates when a new item is added.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyList = new ObservableCollection<Playlists>();
MyListBox.ItemsSource = MyList;
}
private ObservableCollection<Playlists> MyList { get; }
private void Button_Click(object sender, RoutedEventArgs e)
{
MyList.Add(new Playlists(textBox3.Text));
}
}
public class Playlists
{
public Playlists(string title) { Title = title; }
public string Title { get; }
public override string ToString() { return Title; }
}
It seems , you are always creating items with new list. need to add items to existing list.
use below code. it would be useful.
private void button54_Click(object sender, RoutedEventArgs e) {
lbListBox.Items.Add(new Playlists(textBox3.Text, #rutaalbum));
}
Suppose i have created a WPF form having one text box. i am calling that form inside another wpf window's gridpanel and after entering value inside the textbox, i am clicking on submit button. After button click, i need to get that value and save it in string form inside my current class. My logic is something like this.
For getting the from inside my current window:-
void SelectedClick(object sender, RoutedPropertyChangedEventArgs<object> e)
{
selectedItem.ContextMenu = VcontextMenu;
VcontextMenu.Items.Add(VmenuItem1);
VmenuItem1.Click += AddValidation;
details();
}
void AddValidation(object sender, RoutedEventArgs e)
{
ValidationForm obj = new ValidationForm();
ProcessGrid.Content = obj.VForm;
}
Now i want to store the value of my textbox inside a string. For that i have used following code:-
public void details()
{
ValidationForm obj = new ValidationForm();
string str = obj.s.ToString();
}
My ValidationForm Code:-
public partial class ValidationForm : UserControl
{
public string s { get; set; }
public ValidationForm()
{
InitializeComponent();
}
public void XSave_Click(object sender, RoutedEventArgs e)
{
s = TextValidationName.Text;
}
}
but instead of opening the form, the control is going to obj.s.ToString() and showing error as "Object reference not set to an instance of an object." Please help. Thanks.
The issue is caused since the string s in your ValidationForm class is not assigned. It is probably caused since the XSave_Click() method is not being called.
Ensure that you properly assign the value to s before you try to get value from it.
I have a gridview in one form and a combo box in another form.If i select a value in the combo box that value should be passed to the gridview.how can i achieve this...
Your question has too few details, but as a suggestion I'll try to put some code and maybe it'll give you some hint.
// In case if you're dealing with WinForms
// For WPF solution could have similar approach
public class DataGridForm : Form
{
private DataGrid _grid;
public DataGridForm()
{
InitializeComponent();// <-- here _grid is instantiated
}
public void LoadData(object data)
{
// load data into grid
// I don't know, could be smt like
DataGridCell cell = _grid.Cells[0,0];
cell.Value = data;
}
}
public class FormWithComboBox : Form
{
private ComboBox _comboBox;
public DataGridForm DataGridForm { get; set; }// value is set by some externat user
public FormWithComboBox()
{
InitializeComponent();// <-- here _grid is instantiated
// including handler for OnSelectedItemChanged event
}
private void _comboBox_OnSelectedItemChanged(object sender, EventArgs e)
{
DataGridForm.LoadData(_comboBox.SelectedItem);
}
}
I have a listbox full of items for my order.
I want to take all of the items inside my listbox and transfer them into my listview.
Then I want to take my listview and display it in another form (my messagebox).
My new listview:
private void CustomerInfo_Click(object sender, EventArgs e)
{
ListViewItem customers = new ListViewItem(fullName.Text);
customers.SubItems.Add(totalcount.ToString());
customers.SubItems.Add(total.ToString());
customers.SubItems.Add(Address.Text);
customers.SubItems.Add(telephone.Text);
for (int i = 0; i < OrderlistBox.Items.Count; i++)
{
customers.SubItems.Add(OrderlistBox.Items[i].ToString());
}
Customers.Items.Add(customers);
//CLEAR ALL FIELDS
OrderlistBox.Items.Clear();
fullName.Text = "";
Address.Text = "";
telephone.Text = "";
totalDue.Text = "";
totalItems.Text = "";
}
My contextMenuStrip, so when I click on the customer I can get its info (name, address, order, etc.):
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MessageBoxForm
{
name = Customers.SelectedItems[0].SubItems[0].Text,
address = Customers.SelectedItems[0].SubItems[3].Text,
telephone = Customers.SelectedItems[0].SubItems[4].Text,
};
myformmessagedialog.ShowDialog();
}
}
My new form, the messagebox where I will display all the info for the client:
public partial class MessageBoxForm : Form
{
public MessageBoxForm()
{
InitializeComponent();
}
public string name;
public string address;
public string telephone;
public ListViewItem order = new ListViewItem();
private void MessageBoxForm_Load(object sender, EventArgs e)
{
lblName.Text = name;
lbladdress.Text = address;
lbltelephone.Text = telephone;
orderListView.Items.Add(order);
}
}
I'm sorry if this seems confusing but I'm just looking for help to go in the right direction. Any help is appreciated.
One way to do this is to put the data that you want to display in some sort of ViewModel, basically a class or set of classes that has the data that you want to display. Then the main form can display it, and you can pass a reference to that ViewModel to the message box and it can display it as well.
In general you want to avoid any kind of code that directly ties controls from different forms together.
The easiest way based on your current setup is to simply pass your list view data across to your MessageBoxForm e.g.
public partial class MessageBoxForm : Form
{
...
public void LoadListView(ListViewItemCollection items)
{
orderListView.Clear();
orderListView.AddRange(items);
}
}
....
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MessageBoxForm
{
name = Customers.SelectedItems[0].SubItems[0].Text,
address = Customers.SelectedItems[0].SubItems[3].Text,
telephone = Customers.SelectedItems[0].SubItems[4].Text,
};
myformmessagedialog.LoadListView(Customers.Items);
myformmessagedialog.ShowDialog();
}
}
Basic answer is you don't.
You maintain a collection of items (whatever they are).
You display them in a list box.
You display them in a list view.
If you want say select some from the list box and only move them to the list view.
Then you use the listbox selection to find them in your collections of items, create a list of selected ones then passs that to the form with the listview to display.
Don't use UI controls to store your data and try really hard to never make one form's UI directly dependant on another.
I'm guessing what you'd need (and I could have misunderstood what you are looking for) is a new method in you MessageBoxForm to pass in your Customers object:
private void customerInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Customers.SelectedItems.Count != 0)
{
var myformmessagedialog = new MessageBoxForm;
myformmessagedialog.Customers = Customers;
if (myformmessagedialog.ShowDialog() == DialogResult.OK)
{
Customers = myformmessagedialog.Customers;
}
}
}
If so, simply modify your class to be something like this:
public partial class MessageBoxForm : Form
{
public MessageBoxForm()
{
InitializeComponent();
}
private void MessageBoxForm_Load(object sender, EventArgs e)
{
if (Customers != null)
{
// add your code here to add your Customers as needed
}
}
public Customers Customers { get; set; }
}
To access anything from the parent form you need to pass it to the child form so
myformmessagedialog.ShowDialog();
becomes
myformmessagedialog dialog = new myformmessagedialg(this);
dialog.ShowDialog();
and your class constructor becomes this:
public MessageBoxForm(myformmessagedialog parent){
name=parent.fullName.Text;
address=parent.address.Text;
...etc...
InitializeComponent();
}
Though it might be better to just pass in the name, address, etc rather than the whole form, this way is nice for while you are changing things because you have one less place to change to add another variable to pass.