Add item to ListView from another class - c#

I've looked up many question on how to do this, but none of them seem to work. I have a ListView on my main view, and I'm populating it from adding data to it from another form. On the other form, I have a couple strings from text fields I'd like to pass to it. Here's my code:
// Add new booking form:
namespace Booker
{
public partial class newBookingForm : Form
{
public newBookingForm()
{
InitializeComponent();
}
private void NewBookingForm_Load(object sender, EventArgs e)
{
roomField.Focus();
}
private void newBookingButton_Click(object sender, EventArgs e)
{
// Add to ListView
// Add to Parse
string room = this.roomField.Text;
string date = this.datePicker.Value.ToShortDateString();
string time = this.timeField.Text;
string person = "<username>"; // Get current Parse user
Booker booker = new Booker();
string[] array = new string[4] { room, date, time, person };
booker.UpdatingListView(array);
this.Hide();
}
}
}
// ListView form:
namespace Booker
{
public partial class Booker : Form
{
delegate void MyDelegate(string[] array);
public Booker()
{
InitializeComponent();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
Environment.Exit(0);
}
private void Booker_Load(object sender, EventArgs e)
{
listView.View = View.Details;
listView.AllowColumnReorder = false;
}
/* Methods for the Booker form */
private void newBookingButton_Click(object sender, EventArgs e)
{
newBookingForm nbf = new newBookingForm();
nbf.Show();
}
public void UpdatingListView(string[] array)
{
if (this.listView.InvokeRequired)
this.listView.Invoke(new MyDelegate(UpdatingListView), new object[] { array });
else
{
ListViewItem lvi = new ListViewItem(array[0]);
lvi.SubItems.Add(array[1]);
this.listView.Items.Add(lvi);
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Error - no action being sent
}
private void helpButton_Click(object sender, EventArgs e)
{
// Display help panel
}
private void contactButton_Click(object sender, EventArgs e)
{
// Open panel/email
}
private void newBooking_Click(object sender, EventArgs e)
{
newBookingButton_Click(sender, e);
//string[] row = { "Meeting room", "April 11, 2013", "12:00PM-1:00PM", "Ryan" };
//var listViewItem = new ListViewItem(row);
//listView.Items.Add(listViewItem);
}

Try this in UpdatingListView:
ListViewItem lvi = new ListViewItem(array[0],0);
lvi.SubItems.Add(array[1]);
lvi.SubItems.Add(array[2]);
lvi.SubItems.Add(array[3]);
this.listView.Items.Add(lvi);
This will create a column in the first position of your ListView with the 4 items of your array as rows in that column.

To add items from another class, just access the other class' method to add from Program. Like this:
// Class we're adding from:
string name = "Ryan";
string site = "imryan.net";
string[] array = new string[2] = { name, site };
Program.classWithListView.UpdatingListView(array);
// Class we're adding to:
public void UpdatingListView(string[] array)
{
if (this.listView.InvokeRequired)
{
this.listView.Invoke(new MyDelegate(UpdatingListView), new object[] { array });
} else {
ListViewItem lvi = new ListViewItem(array[0]);
lvi.SubItems.Add(array[1]);
lvi.SubItems.Add(array[2]);
this.listView.Items.Add(lvi);
}
}
The string array will be added to the ListView as SubItems.

Related

Manipulating similar objects in a form using another form

I am new to C# and I want to utilize the forms with one another.
I have 2 forms. (1)MMCMLibrary_home and (2)MMCMLibrary_reserve.
In this project, I'm in the stage of changing the label background colors in Form 1 but can't seem to utilize Form 2 to process it.
These are my necessary codes so far:
FORM 1
namespace MMCM_Library
{
public partial class MMCMLibrary_home : Form
{
public static MMCMLibrary_home instance;
//DCR1 Labels
public Label lbl1_1;
public Label lbl1_2;
public Label lbl1_3;
public Label lbl1_4;
public MMCMLibrary_home()
{
InitializeComponent();
instance = this;
lbl1_1 = lblDCR1_9;
lbl1_2 = lblDCR2_11;
lbl1_3 = lblDCR1_1;
lbl1_4 = lblDCR1_3;
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve();
reserveDCR1.Show();
}
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve();
reserveDCR2.Show();
}
public void btnDCR3_Click(object sender, EventArgs e)
{
var reserveDCR3 = new MMCMLibrary_reserve();
reserveDCR3.Show();
}
public void btnDCR4_Click(object sender, EventArgs e)
{
var reserveDCR4 = new MMCMLibrary_reserve();
reserveDCR4.Show();
}
}
}
FORM 2
when I click any reserve now button in form 1 it will open form 2. However, if I pick a radio button, the background change will always be applied to Discussion Room 1 even I reserved for discussion room 2
namespace MMCM_Library
{
public partial class MMCMLibrary_reserve : Form
{
public static MMCMLibrary_reserve instance;
public MMCMLibrary_reserve()
{
InitializeComponent();
instance = this;
}
private void MMCMLibrary_reserve_Load(object sender, EventArgs e)
{
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged_1(object sender, EventArgs e)
{
}
private void btnDCR1_Click(object sender, EventArgs e)
{
}
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
}
}
}
Can you help me to device an efficient way to solve this. Can you also suggest a database method suitable for my beginner project.
You've said that:
the background change will always be applied to Discussion Room 1
Well, yes. It seems you don't pass specific object into Form2. There's strightforward:
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
So you'll be always changing backcolor of lbl1_1 of your Form1. What needs to be done is to indicate which room has been selected. You can assign room after you click the button by passing the int parameter:
public void btnDCR1_Click(object sender, EventArgs e)
{
var reserveDCR1 = new MMCMLibrary_reserve(1);
reserveDCR1.Show();
}
or:
public void btnDCR2_Click(object sender, EventArgs e)
{
var reserveDCR2 = new MMCMLibrary_reserve(2);
reserveDCR2.Show();
}
Then, in Form2, at the very top, add something like:
int room; to be able to assign the room number in Form2:
public MMCMLibrary_reserve(int roomNumber)
{
InitializeComponent();
room = roomNumber;
instance = this;
}
And then you could just select room you clicked, by:
public void btnDCRoomsReserve_Click(object sender, EventArgs e)
{
if (rbtn9.Checked)
{
if(room == 1)
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
else if(room == 2)
{
MMCMLibrary_home.instance.lbl1_2.BackColor = System.Drawing.Color.Red;
}
else if(room == 3)
{
MMCMLibrary_home.instance.lbl1_3.BackColor = System.Drawing.Color.Red;
}
else if(room == 4)
{
MMCMLibrary_home.instance.lbl1_4.BackColor = System.Drawing.Color.Red;
}
}
else if(radioButton2.Checked)
{
//etc.
}
else if(radioButton3.Checked)
{
//etc.
}
else if(radioButton4.Checked)
{
//etc.
}
}
I think that was the problem. Try it and let us know.

avoid initializing list with data

So, I have two forms. The form1 has a button to open the form2. In the form2 I have a list of elements that I fill with elements I create in the form2. My problem is, when I close my form2 and reopen it, my list is empty. I know that is because Im initializing my list again (ListaComida = new List<Comida>();), so I get my data erased but I dont see how to solve this.
My code
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addDia_Click(object sender, EventArgs e)
{
string dia = (DateTime.Today.ToString("dd/MM/yyyy"));
TabPage myTabPage = new TabPage(dia);
tabControl1.TabPages.Add(myTabPage);
}
private void AddComida_Click(object sender, EventArgs e)
{
FormAddComida addComida = new FormAddComida();
DialogResult resultaod = addComida.ShowDialog();
}
}
Form2
public partial class FormAddComida : Form
{
public List<Comida> ListaComida;
public FormAddComida()
{
InitializeComponent();
ListaComida = new List<Comida>();
}
private void addComidaAdicionar_Click(object sender, EventArgs e)
{
Comida comidaAdicionada = new Comida(tbNome.Text,
Convert.ToInt32(tbCalorias.Text),
Convert.ToInt32(tbHidratos.Text),
Convert.ToInt32(tbProteinas.Text),
Convert.ToInt32(tbGorduras.Text)
);
ListaComida.Add(comidaAdicionada);
RefreshListaComida();
}
private void RefreshListaComida()
{
lbListaComida.Items.Clear();
lbListaComida.Items.AddRange(ListaComida.ToArray());
}
private void AddComidaCancelar_Click(object sender, EventArgs e)
{
this.Close();
}
}
You can use MemoryCache, even if you close your form your List will stay in Memory and you can retrieve by the Key. But if you need to save this data permanently (or long time running the app )i recommend you store in a DB.
using System.Runtime.Caching;
private ObjectCache cache = MemoryCache.Default;
public class Food
{
public string Name { get; set; }
public double Price { get; set; }
}
public void AddFood()
{
FoodList.Add(new Food { Name = "Pizza", Price = 10 });
FoodList.Add(new Food { Name = "Fries", Price = 5 });
cache.Add("UserCacheFood", FoodList, DateTimeOffset.MaxValue);
}
public List<Food> ReturnListFromCache()
{
return (List<Food>)cache.Get("UserCacheFood");
}
private void button1_Click(object sender, EventArgs e)
{
AddFood();
var result = ReturnListFromCache();
}
private void button2_Click(object sender, EventArgs e)
{
var ret2 = ReturnListFromCache();
}

How to create Dialog Box with Radio Buttons and return Value

I have a List of Objects. What I want to do:
Build a Dialog Box which shows a Radio Button for each element in the given List and returning the selected element/value by clicking on OK-Button.
Thanks in Advance.
Here is a quick example of creating your own form and getting a value from it.
Form1.cs:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frmTest frmTest = new frmTest();
DialogResult dr = frmTest.ShowDialog();
if(dr == System.Windows.Forms.DialogResult.OK)
{
string value = frmTest.GetValue();
MessageBox.Show(value);
}
}
}
Form1 View:
public partial class frmTest : Form
{
private string _value { get; set; }
public frmTest()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton radioButton = (RadioButton)sender;
this._value = radioButton.Text; // Assign the radio button text as value Ex: AAA
}
public string GetValue()
{
return this._value;
}
}
You have to make sure that all radio buttons are using radioButton_CheckedChanged for the CheckedChanged event.
Form2 View:
Output:
build your own form and add a public variable "a string for example" called "Result"
public partial class YourDialog:Form
{
public string Result = "";
public YourDialog()
{// add all the controls you need with the necessary handlers
//add the OK button with an "On Click handler"
}
private void OK_Button_Click(object sender, EventArgs e)
{
//set the Result value according to your controls
this.hide();// will explain in the main form
}
}
// in your main form
private string GetUserResult()
{
YourDialog NewDialog = new YourDialog();
NewDialog.ShowDialog();//that's why you only have to hide it and not close it before getting the result
string Result = NewDialog.Result;
NewDialog.Close();
return Result;
}
OOps! I came back just to see there are already 2 answers! How ever, I want to post my version, which can build controls according to list of strings:
//dialog form
public partial class frmDialogcs : Form
{
public string selectedString;
//keep default constructor or not is fine
public frmDialogcs()
{
InitializeComponent();
}
public frmDialogcs(IList<string> lst)
{
InitializeComponent();
for (int i = 0; i < lst.Count; i++)
{
RadioButton rdb = new RadioButton();
rdb.Text = lst[i];
rdb.Size = new Size(100, 30);
this.Controls.Add(rdb);
rdb.Location = new Point(20, 20 + 35 * i);
rdb.CheckedChanged += (s, ee) =>
{
var r = s as RadioButton;
if (r.Checked)
this.selectedString = r.Text;
};
}
}
private void btnOK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
//in main form
private void button1_Click(object sender, EventArgs e)
{
var lst = new List<string>() { "a", "b", "c" };
frmDialogcs dlg = new frmDialogcs(lst);
if (dlg.ShowDialog() == DialogResult.OK)
{
string selected = dlg.selectedString;
MessageBox.Show(selected);
}
}

c# how to add string in of the line values in RichTextBox

namespace PostingQueueMonitoring_V2
{
public partial class Helper : Form
{
public Helper()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(input_richTextBox1.Text.Trim()))
{
MessageBox.Show("Please input text...");
return;
}
string[] myText = new string[] {input_richTextBox1.Text};
foreach (string element in myText)
{
output_richTextBox2.Text = element;
System.Console.WriteLine(output_richTextBox2.Text);
}
System.Console.WriteLine();
//output_richTextBox2.Rtf = input_richTextBox1.Rtf;
}
private void Helper_Resize(object sender, EventArgs e)
{
this.MinimumSize = new Size(736, 466);
this.MaximumSize = new Size(736, 466);
}
}
}
How to update the code that will format the text from input_richTextBox1 and shown in output_richTextBox2. Example below.
input_richTextBox1:
Apple\n
Banna\n
Coconut\n
Durian\n
Orange
Expected Result into output_richTextBox2
('Apple',
'Banna',
'Coconut',
'Durian',
'Orange')
Please try this.
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(richTextBox1.Text.Trim()))
{
MessageBox.Show("Please input text...");
return;
}
var textValues = richTextBox1.Text.Split('\n').Select(txt => $"'{txt}'");
var concatValues = string.Join(",", textValues);
richTextBox2.Text = concatValues;
System.Console.WriteLine();
}

gallery switcher( c# visual)

Why does this not work?
There are two Radio buttons.
If I check radio button1 I should see gallery1.
If I check Radio button2 I should see galery2.
And button1"<<" button2 ">>" is meant to view gallery : back, forward.
http://s1v3.irc.lv/files/1/0/0/454/KddPouO7.png
http://s1v2.irc.lv/files/1/0/0/454/aHPiAt4k.png
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<string> galerija1;
List<string> galerija2;
List<string> aktualaGalerija;
int tekosaPozicija;
string galerija1 = new List<string>(){ "C:\\Galerija1\\aq1.png", "C:Galerija1\\aq2.png"};
string galerija2 = new List<string>(){ "C:Galerija2\\dr1.png", "C:Galerija2\\dr1.png"};**
///// He don`t like this place :( Someone can help?
public Form1()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
aktualaGalerija = galerija1;
tekosaPozicija = 0;
IeladeAktualoBildi();
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
aktualaGalerija = galerija2;
tekosaPozicija = 0;
IeladeAktualoBildi();
}
private void IeladeAktualoBildi()
{
string aktualaBilde = aktualaGalerija[tekosaPozicija];
}
private void button2_Click(object sender, EventArgs e)
{
if (tekosaPozicija == aktualaGalerija.Count - 1)
return;
tekosaPozicija++;
IeladeAktualoBildi();
}
private void button1_Click(object sender, EventArgs e)
{
if (tekosaPozicija == 0)
return;
tekosaPozicija--;
IeladeAktualoBildi();
}
}
}
Replace
List<string> galerija1;
string galerija1 = new List<string>(){ ... };
with
List<string> galerija1 = new List<string> { ... };
The same with galerija2. Your code declares two fields with the same name, but different types.

Categories