I have 2 forms, form1 and form2.
form1 has 2 buttons, btnVanilla and btnConfirm.
form2 has a listView, listView1.
On form1 when vanilla is clicked once, it should show "1" in Quantity column next to Vanilla.
But at the moment it is showing "1" underneath vanilla. How do I move it across onto the next column?
There is a screenshot which shows what I mean.
form1
public partial class form1 : Form
{
private string vanilla = "Vanilla";
private List<string> _values = new List<string>();
public form1()
{
InitializeComponent();
}
int vanillaCount = 0
public void btnVanilla_Click(object sender, EventArgs e)
{
if (!_values.Contains(vanilla))
{
_values.Add(vanilla);
}
vanillaCount++;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
form2 frm2 = new form2(_values, vanillaCount);
frm2.Show();
this.Hide();
}
}
form2
public partial class form2 : Form
{
private List<string> _values;
public form2(List<string> _values)
{
this._values = _values;
}
public form2(List<string> passedValues, int vanillaCount)
{
InitializeComponent();
foreach (var item in passedValues)
{
listView1.Items.Add(item);
}
listView1.Items[0].SubItems[1].Text = vanillaCount.ToString();
}
}
Are you sure that this line
listView1.Items[0].SubItems[1].Text = vanillaCount.ToString();
is correct? You aren't creating subitem anywhere, it should be like
listView1.Items[0].SubItems.Add(vanillaCount.ToString());
One solution for your actual problem:
public Form2(List<string> passedValues, int vanillaCount)
{
InitializeComponent();
// This line let you show more Columns
listView1.View = View.Details;
// Define your needed Columns
listView1.Columns.Add("Item-Name", -2); //(the width with -2 means, that the column will be autosized)
listView1.Columns.Add("Quantity");
foreach (var item in passedValues)
{
// Create a new ListViewItem "Vanilla", add your needed Subitems like Quantity, Price, ...
var newItem = new ListViewItem(item);
newItem.SubItems.Add(vanillaCount.ToString());
// add the new Item to your ListView
listView1.Items.Add(newItem);
}
}
But you should create a list with a own object-type like
public class Product
{
public string Name { get; set; }
public int Quantity { get; set; }
}
For your problem use like this:
ListViewItem row = new ListViewItem();
row.SubItems.Add(value.ToString());
listview1.Items.Add(row);
you repeat the second row as many times as you have columns in the listview
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 2 forms, form1 and form2. Whenever I double click on a cell of datagrid in form1, it will go form 2 and there I am displaying some items and price of them in a datagrid. I am selecting one row there and that value is passing form 1 datagridview. but I want to pass second valu that also over writing first passed value of form 1. I want to add that in next row. What do I have to do?
Here is my code of form 2
private void Form2_Load(object sender, EventArgs e)// loading data to datagrid from database file
{
SqlDataAdapter sda = new SqlDataAdapter(#"select brnDb.compname as [company name], brnDb.catname as [category Name], itemDB.fullname as [Item Name], itemDb.itmbyp as [Buying Price], itemDB.itmdlrp [Dealer Price],itemDB.itmmrp as [MRP],itemDb.itmunit as [Unit Of Measure], itemDB.itmml [Liters], itemDB.itmgr[KGs], itemDb.itmpc[Units] from brnDB inner join itemDb on brnDb.brname=itemDB.brname order by itemDB.fullname asc", con);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
passing selected row with a button click to form 1
private void button1_Click(object sender, EventArgs e)
{
Form1 b = new Form1(dataGridView1.SelectedRows[0].Cells[2].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[3].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[4].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[5].Value.ToString());
b.ShowDialog();
}
Code of form 1
public Form1(string Item_Name, string Buying_Price, string Dealrer_Price, string MRP )
{
InitializeComponent();
int n;
n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[1].Value = Item_Name;
dataGridView1.Rows[n].Cells[3].Value = Buying_Price;
dataGridView1.Rows[n].Cells[4].Value = Dealrer_Price;
dataGridView1.Rows[n].Cells[5].Value = MRP;
}
So value is being passed from form 2 but overwriting in first row each time. But I want to add new row in form1 before passing.Maybe I want to use some loops here but I don't know how. for looping purpose I took declared a integer also. I googled for that but end up with no good result.
You have to add a List in form1 which can be accessed in form2.
Define Form1 b = null; as global variable
Add b = new Form1(); Form2_Load function
Add b.list.Add(dataGridView1.SelectedRows[0]); to button1_click function before ShowDialog();
Keep only b.ShowDialog(); line in button1_click function
Add public List<DataGridViewRow> list = new List<DataGridViewRow>(); to form1
We can also have another option is to create static class that have generic list . We can use that list as temporary storage.
static class Global
{
private static List<GridRows> _globalVar = new List<GridRows>();
public static void ResetGridData()
{
_globalVar = new List<GridRows>();
}
public static GridRows SetRow
{
set { _globalVar.Add(value); }
}
public static List<GridRows> GetSetting { get { return _globalVar; } }
public class GridRows
{
public string Cell_1 { get; set; }
public string Cell_2 { get; set; }
public string Cell_3 { get; set; }
public string Cell_4 { get; set; }
}
}
This class have public static SetRow setter. Use this setter to save data in global list which is "_globalVar ".
This class also have method to reset that list in any point. Just call that static method to reset that grid.
How to use
This is form2 code that get data and pass to form1.
public partial class Form2 : Form
{
public Form2()
{
//To reset our temporary store on load
Global.ResetGridData();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Send data from form 2 to form 1
Form1 b = new Form1(dataGridView1.SelectedRows[0].Cells[2].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[3].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[4].Value.ToString(),
dataGridView1.SelectedRows[0].Cells[5].Value.ToString());
b.ShowDialog();
}
}
Receive and save data to our global list in form 1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1(string cell1, string cell2, string cell3, string cell4)
{
InitializeComponent();
//Save data to our list using global class that
Global.SetRow = new Global.GridRows()
{
Cell_1 = cell1,
Cell_2 = cell2,
Cell_3 = cell3,
Cell_4 = cell4
};
}
}
For example i have these values stored in the listbox.
int pid = (int)reader["pid"];
string FirstName = (string)reader["Fname"];
string LastName = (string)reader["Lname"];
string gender = (string)reader["gender"];
string address = (string)reader["address"];
string email = (string)reader["email"];
string item = string.Format("{0} - {1} - {2} -{3} - {4} - {5}" pid,FirstName, LastName,gender,address,email);
this.listBox1.Items.Add(item);
How do i pass these items to another class method ?
Thanks
You can pass it like that:
public void YourMethod(ListBox.ObjectCollection items)
using:
YourMethod(listBox1.Items);
UPD: I created a windows form with empty listbox and 1 button. Clicking on button fills the listbox. Form1 class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
var itemGenerator = new ItemGenerator();
itemGenerator.AddItems(listBox1);
}
}
ItemGenerator class:
public class ItemGenerator
{
private readonly string[] items = {"item1", "item2", "item3"};
public void AddItems(ListBox listBox)
{
foreach (var item in items)
{
listBox.Items.Add(item);
}
}
}
ItemGenerator has method AddItems which has ListBox in parameter. This method is called in Form1 class, so you can directly give a ListBox to processing.
Well I know this question has been asked a couple of times but none of the solutions worked for me. I simply want to pass a value from one form to a textbox in a different form.
On the first form I have a data grid when double-clicked on it obtains a value from the datagrid column.
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
RoomBooking rb = new RoomBooking();//The second form
rb.roomnumber = roomnum;
rb.Show();
}
}
On the second form I have set the properties of the textbox
public partial class RoomBooking : Form
{
public RoomBooking()
{
StartPosition = FormStartPosition.CenterScreen;
InitializeComponent();
}
public string roomnumber
{
get { return txtRoomNum.Text; }
set {txtRoomNum.Text = value;}
}
}
Thanks in advance for the help?
You have to find the control to edit it as it does not belong to the class.
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
//new value
var roomnum = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
//The second form
RoomBooking rb = new RoomBooking(this);
//The textbox
TextBox roomnumber = (TextBox)rb.Controls.Find("roomnumber", true)[0];
//set the value of the textbox
roomnumber.Text = roomnum;
//show second form
rb.Show();
}
I would define the RoomBookingclass like this:
public partial class RoomBooking : Form
{
public RoomBooking() // WinForms Designer requires a public parameterless constructor
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
}
public RoomBooking(string roomNumber) : this() // Constructor chaining
{
RoomNumber = roomNumber;
txtRoomNum.Text = RoomNumber;
}
public string RoomNumber { get; set; }
}
Then:
public partial class AvailableRooms : Form
{
private void DCRoom(object sender, DataGridViewCellMouseEventArgs e)
{
var roomNumber = dgRooms.Rows[e.RowIndex].Cells["iRoomNum"].Value.ToString();
var roomBooking = new RoomBooking(roomNumber);
roomBooking.Show();
}
}
Hope this helps.
I have a listview in my Mainform and I need to get the value in the textbox and label in the other form name Add_Order?
Add_Order add = new Add_Order();
ListViewItem item = new ListViewItem();
item.Text = add.textBox3.Text;
item.SubItems.Add(add.label6.Text);
item.SubItems.Add(add.textBox2.Text);
item.SubItems.Add(add.textBox1.Text);
item.SubItems.Add(add.textBox3.Text);
mainform.listView2.Items.Add(item);
I personally would not expose the controls in your Add_Order Form. Your calling Form should not be aware of the internals of the Add_Order Form, only its public Methods and Properties. I would make a Public Method and use that to retrieve the information you need. something like this:
Add_Order.cs
public partial class Add_Order : Form
{
public Add_Order()
{
InitializeComponent();
}
public List<string> GetData()
{
List<string> list = new List<string>();
list.Add(textBox3.Text);
list.Add(label6.Text);
list.Add(textBox2.Text);
list.Add(textBox1.Text);
return list;
}
}
MainForm
private void button1_Click(object sender, EventArgs e)
{
Add_Order add = new Add_Order();
add.ShowDialog();
ListViewItem item = new ListViewItem();
List<string> data = add.GetData();
item.Text = data[0];
item.SubItems.Add(data[1]);
item.SubItems.Add(data[2]);
item.SubItems.Add(data[3]);
item.SubItems.Add(data[0]);
listView2.Items.Add(item);
}
You can pass the data to other forms in different ways like creating public classes to maintain data common data between forms or you can pass data using form constructor like :
Add_Order frmAddOrder=new Add_Order(data1,data2);
frmAddOrder.show();
and in your Add_Order Constructor :
public Add_Order (string data1,string data2)
{
InitializeComponent();
//you can access data1 and data2 here ...
}
I write a simple one for you:
Set element Modifiers to true in Add_Order form :
and get it in main form:
public partial class main : Form
{
public main()
{
InitializeComponent();
Get_Frm2_Data();
}
private void Get_Frm2_Data()
{
Add_Order frm2 = new Add_Order();
List<string> info= new List<string>;
info.Add( frm2.textBox1.Text);
.
.
.
}
}
edit
or make an structure:
Add_Order.cs
public partial class Add_Order : Form
{
public Add_Order()
{
InitializeComponent();
}
public Info Get_Data()
{
return new Info() { _textBox3 = textBox3.Text,
_label6 = label6.Text,
_textBox2 = textBox2.Text,
_textBox1 = textBox1.Text,
};
}
}
struct Info
{
public string _textBox3;
public string _label6;
public string _textBox2;
public string _textBox1;
}
Mainform.cs
public partial class main : Form
{
public main()
{
InitializeComponent();
Get_Frm2_Data();
}
private void Get_Frm2_Data()
{
Add_Order frm2 = new Add_Order();
frm2.ShowDialog();
Info lst_data= frm2.Get_Data();
ListViewItem item = new ListViewItem();
item.Text = lst._textBox3;
item.SubItems.Add(lst._label6);
item.SubItems.Add(lst._textBox2);
item.SubItems.Add(lst._textBox1);
mainform.listView2.Items.Add(item);
}
}