Passing data to DataGridViews - c#

I have text boxes on my second form and a send button which is in the code shown below.
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.PassName = richTextBox1.Text;
f1.PassLastName = richTextBox2.Text;
f1.PassAge = comboBox1.Text;
f1.PassGender = richTextBox3.Text;
f1.ShowDialog();
}
and a DataGridView on form 1 with this code
public partial class Form1 : Form
{
private string name;
private string lastName;
private string age;
private string gender;
public string PassName
{
get { return name; }
set { name = value; }
}
public string PassLastName
{
get { return lastName; }
set { lastName = value; }
}
public string PassAge
{
get { return age; }
set { age = value; }
}
public string PassGender
{
get { return gender; }
set { gender = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = name;
dataGridView1.Rows[n].Cells[1].Value = lastName;
dataGridView1.Rows[n].Cells[2].Value = age;
dataGridView1.Rows[n].Cells[3].Value = gender;
}
private void mnuExit_Click(object sender, EventArgs e) //adding the quit on the top file with caution message
{
if (MessageBox.Show("Do you really want to Quit?", "Exit", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
Application.Exit();
}
}
private void addTask_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(); //show form2 so user can input data
f2.ShowDialog();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}`
This is fine if I want to send one set of data to the DataGridView, but if I add new information again then this opens a new DataGridView and stores it to another seperate DataGridView then I have two DataGridView forms. I want to put all the data onto one DataGridView and keep adding rows. So when the user clicks the add button on the first form with the DataGridView, it opens up the TextBox form which is form 2, then the user fills out the information and clicks the send button which sends the information back to the DataGridView, however this then opens up a new window with a new DataGridView. I dont want this to happen I want it to keep adding rows on the first form.
Could someone show me how to do this?

You can use ShowDialog(this) and Owner to get the parent form's property.
Form1
private void Form1_Load(object sender, EventArgs e)
{
//Move to Form1_Activated
this.Activated += new System.EventHandler(this.Form1_Activated); //connect
}
private void Form1_Activated(object sender, EventArgs e)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = name;
dataGridView1.Rows[n].Cells[1].Value = lastName;
dataGridView1.Rows[n].Cells[2].Value = age;
dataGridView1.Rows[n].Cells[3].Value = gender;
}
private void addTask_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(); //show form2 so user can input data
f2.ShowDialog(this);//set this form as Owner
}
Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = (Form1)this.Owner;//Get the Owner form
f1.PassName = richTextBox1.Text;
f1.PassLastName = richTextBox2.Text;
f1.PassAge = comboBox1.Text;
f1.PassGender = richTextBox3.Text;
//f1.ShowDialog();
f1.Show();
this.Close();
}

Related

Passing values from form1 to form2 via button click to form2 [duplicate]

This question already has an answer here:
How to open new form, pass parameter and return parameter back
(1 answer)
Closed 4 years ago.
frmPlaceOrder is my form1. I need to pass the firstName, lastname and Address from this form to the second one which will do the other functions. I don't know how to do that.
namespace Lab1_OrderCake
{
public partial class frmPlaceOrder : Form
{
public static CustomerInformation customer;
public static Address address;
public frmPlaceOrder()
{
InitializeComponent();
customer = new CustomerInformation(txtFName.Text, txtLName.Text);
address = new Address(txtAddress.Text, txtCity.Text, txtPC.Text, txtProvince.Text);
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
if (txtFName.Text == "")
{
MessageBox.Show("Please enter first name", "Data Missing");
txtFName.Focus();
return;
}
if (txtLName.Text == "")
{
MessageBox.Show("Please enter Last name", "Data Missing");
txtLName.Focus();
return;
}
else
{
frmCakeOrder newCust = new frmCakeOrder();
this.Hide();
newCust.ShowDialog();
this.Close();
}
}
}
}
The second form; after the first one has been filled out needs to take the values from form1 and display it with the other values(frmCakeOrder values) in the second form. It needs to be seen in the View and Order events when i click it.
here is the Second form:
namespace Lab1_OrderCake
{
public partial class frmCakeOrder : Form
{
Order cakeOrder;
public List<Cake> cakeList;
public frmCakeOrder()
{
InitializeComponent();
cmbTraditionalCake.SelectedIndex = 0;
cakeOrder = new Order();
gbCustomCake.Visible = false;
this.Size = new Size(700,360);
cakeList = new List<Cake>();
}
private void bttnOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Confirm Order", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlgMsg == DialogResult.Yes)
{
MessageBox.Show(cakeOrder.PrintConfirmation());
}
else
{
MessageBox.Show ("The order has not been placed");
}
bttnReset.Focus();
cakeOrder.ClearCart();
}
private void radCustom_CheckedChanged(object sender, EventArgs e)
{
if (radCustom.Checked)
{
cmbTraditionalCake.Enabled = false;
gbCustomCake.Visible = true;
}
else
{
cmbTraditionalCake.Enabled = true;
gbCustomCake.Visible = false;
}
}
private void btnView_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
cakeOrder.NumOfCakes=1;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Your order: ", MessageBoxButtons.YesNo , MessageBoxIcon.Information);
if (dlgMsg == DialogResult.No)
{
cakeOrder.ClearCart();
MessageBox.Show("Please enter and confirm your order!");
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (radCustom.Checked)
{
string flavour, occasion;
flavour = occasion = "";
int layers;
//for flavor
if (radBanana.Checked)
flavour = "Banana";
else if (radChocolate.Checked)
flavour = "Chocolate";
else if (radVanilla.Checked)
flavour = "Vanilla";
if (radTier2.Checked)
layers = 2;
else if (radTier3.Checked)
layers = 3;
else
layers = 1;
if (radGraduation.Checked)
occasion = radGraduation.Text.TrimStart(new char[] { '&' });
else if (radWedding.Checked)
occasion = radWedding.Text.TrimStart(new char[] { '&' });
else occasion = radAnniversary.Text.TrimStart(new char[] { '&' });
cakeOrder.AddCake(new Custom(flavour, occasion, layers));
}
else
{
cakeOrder.AddCake(new Traditional(cmbTraditionalCake.SelectedItem.ToString()));
}
cakeList.Add(cakeOrder);
}
}
}
There are many ways to do this. Try it this way.
private void btnPlaceOrder_Click(object sender, EventArgs e) {
string fname = textBox1.Text;
frmCakeOrder frm = new frmCakeOrder(textBox1.Text);
frm.Show();
}
And in frmCakeOrder,
public frmCakeOrder(string fname) {
InitializeComponent();
textBox1.Text = fname;
}
You can pass the data in the constructor:
public class Form1: from{
//constructor
public void Form1(){
}
public void button_click(){
//Get the data
var firstName = textFirstName.text;
var secondName= textSecondName.text;
var address= textAddress.text;
//Pass the data on the constructor of Form2
Form2 f2 = new Form2(firstName,secondName, address);
f2.show();
}
}
public class Form2: Form{
//constructor with data or parameters
public void Form2(string firstName, string lastName, string Address){
//do dosomething with the data
txtFirstName.text = firstName;
}
}
*sorry if it has sintaxys errors.... but thats the idea.

Passing Value from One Form to Another (C#)

I have a search form in my program. When the user double-clicks a cell (of the dgv) on the search form, I want the program to close that form and jump to the item on the main form.
I'm doing this by identifying each item with a unique id.
I'm trying to pass the value of the rows id to the other form. The problem is that, it says that I'm passing the value zero each time. But when I insert some message boxes on the search form, it says that the integer 'id' has successfully been assigned to the variable on the main form: public int CellDoubleClickValue { get; set; }
Here is my code:
Search Form:
private int id;
private void searchdgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
this.rowIndex1 = e.RowIndex;
this.id = Convert.ToInt32(this.searchdgv.Rows[this.rowIndex1].Cells["id"].Value);
invmain inv = new invmain();
inv.CellDoubleClickValue = this.id;
this.DialogResult = DialogResult.OK;
this.Close();
//MessageBox.Show(inv.CellDoubleClickValue.ToString());
//Above, it shows it got assigned successfully.
}
Main Form:
public int CellDoubleClickValue { get; set; }
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
search form1 = new search();
form1.ShowDialog();
if (form1.DialogResult == DialogResult.OK)
{
MessageBox.Show(CellDoubleClickValue.ToString());
}//Here it shows that the value is: 0
I suggest you do as follows:
Search Form:
public int SelectedId { get; set; }
private void searchdgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
this.rowIndex1 = e.RowIndex;
this.SelectedId = Convert.ToInt32(this.searchdgv.Rows[this.rowIndex1].Cells["id"].Value);
this.DialogResult = DialogResult.OK;
this.Close();
}
Main form:
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
search form1 = new search();
form1.ShowDialog();
if (form1.DialogResult == DialogResult.OK)
{
int selectedId = form1.SelectedId;
// Do whatever with selectedId...
}

send TextBox Values from FormB to a datagridView in FormA

I have to send the value of 2 TextBoxes from FormB when I clic on the "validate buton" to the datagridView in FormA;this is what I try to code:
FormB:
namespace RibbonDemo.Fichier
{
public partial class NvFamillImmo : Form
{
public event BetweenFormEventHandler BetweenForm;
SqlDataAdapter dr;
DataSet ds = new DataSet();
string req;
public NvFamillImmo()
{
InitializeComponent();
affich();
}
private void button2_Click(object sender, EventArgs e) //the validate buton
{
if (BetweenForm != null)
BetweenForm(textBox1.Text, textBox2.Text);
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.amortissementFiscalTableAdapter.FillBy(this.mainDataSet.amortissementFiscal);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
}
and this is FormA:
namespace RibbonDemo.Fichier
{
public delegate void BetweenFormEventHandler(string txtbox1value, string txtbox2value);
public partial class FammileImm : Form
{
private NvFamillImmo nvFamillImmo;
public FammileImm()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
NvFamillImmo frm2 = new NvFamillImmo();
frm2.BetweenForm += frm2_BetweenForm;
frm2.ShowDialog();
}
void frm2_BetweenForm(string txtbox1value, string txtbox2value)
{
//dataGridView1.Refresh();
String str1 = nvFamillImmo.textBox1.Text.ToString();
this.dataGridView1.Rows[0].Cells[0].Value = str1;
}
}
}
EDIT:I filled the method frm2_BetwwenForm but now I get a problem in reference
thanks for Help
No Need to create event for that. you can create properties in second form where you want to send value from existing form. for example if you have two forms FormA and FormB then FormB should contains properties like Value1 and Value2.
//FormB
public class FormB :Form
{
public string Value1{get; set;}
public string Value2{get; set;}
}
Now you can assign value into both properties from FormA.
//FormA
public void button1_click(object sender, EventArgs e)
{
FormB myForm = new FormB();
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
myForm.Show();
}
Then you can get both textboxes value into FormB. You can handle value into Form Load event
//FormB
public void FormB_Load(object sender, EventArgs e)
{
string fromTextBox1 = this.Value1;
string formTextBox2 = this.Value2;
}
If the FormB is already loaded and want to send value from FormA then create a method UpdateValues() and modify the properties to call that method.
//FormB
string _value1 = string.Empty;
public string Value1
{
get { return _value1; }
set {
_value1 = value;
UpdateValues();
}
}
string _value2 = string.Empty;
public string Value1
{
get { return _value2; }
set {
_value2 = value;
UpdateValues();
}
}
private void UpdateValues()
{
string fromTextBox1 = this.Value1;
string fromTextBox2 = this.Value2;
}
and Assign the values in FormB.Value1 and FormB.Value2 properties from FormA.
//FormA
FormB myForm = new FormB();
public void button1_click(object sender, EventArgs e)
{
if (myForm != null && myForm.IsDisposed == false)
{
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
}
}
When the value is updated from FormA then UpdateValues() method will be called.

Adding data to a gridview in c# from multiple forms

How would I go about inserting the text that I have entered in to the textbox in NewActivity into the first column in the datagridview on form1?
Here is the coding I have thus far.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.IsMdiContainer = true;
}
private void viewToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void newActivityToolStripMenuItem_Click(object sender, EventArgs e)
{
NewActivity NewAc = new NewActivity();
NewAc.MdiParent = this;
NewAc.Show();
}
private void deleteActivityToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
NewActivity
public partial class NewActivity : Form
{
public string activityName;
public NewActivity()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
activityName = "";
this.Close();
}
private void btnAddActivity_Click(object sender, EventArgs e)
{
activityName = txtActivityName.Text;
this.Close();
}
}
}
you can insert it in your event click
private void btnAddActivity_Click(object sender, EventArgs e)
{
activityName = txtActivityName.Text;
int index = yourDataGridView.Rows.Add();
DataGridViewRow row = yourDataGridView.Rows[index];
row.Cells[0].Value = activityName ;
this.Close();
}
Here is an example of how to bind data from a textbox control to a DataGrid
// create new row
DataGridViewRow row = new DataGridViewRow();
// create cells
row.CreateCells(this.dataGridView1, textBox1.Text, textBox2.Text, textBox3.Text);
// add to data grid view
this.dataGridView1.Rows.Add(row);
---------------Below is how you would use it in your case--------------------
private void btnAddActivity_Click(object sender, EventArgs e)
{
activityName = txtActivityName.Text;
int index = dgvActivityList .Rows.Add();
DataGridViewRow row = dgvActivityList .Rows[index];
row.Cells[0].Value = activityName;
this.Close();
}

C# how to edit listview items from new form?

So I have a ListView that is populated with information and edit button in form1.
Now when i select item in ListView and click edit, I want it to bring me to form2 and display selected items data.
For example, I select name from ListView hit edit it brings me to form2 where is TextBox, lets say textbox1 = Name and textbox2 = Age and in my List<data> have 2 items in it name and age.
What i need now is, when I select one of the ListView items and pres edit it opens form2 and loads name in textbox1 and age in textbox2 how can I do that ?
I was trying listview_SelectedIndexChanged event like this :
Form2 edit = new Form2();
edit.textBox1.Text = People[this.listView1.SelectedItems[0].Index].Name;
edit.textBox2.Text = People[this.listView1.SelectedItems[0].Index].Age;
Is there any way to reference this to button click edit? or is there another way?
and how do I save changes afterwards?
Pass in the value in the form of constructor .
In your main form where you have your listbox store the value of the listbox selected value in a variable and then in your button edit event call the constructor of the 2nd form
Form2 child= new Form2(Name,Age);
Form2.show()
In the 2nd form create global variables for name and age
private string _name = String.Empty;
private int _age;
Then create a constructor for your 2nd form
public void Form2(string name, int age)
{
InitializeComponent();
this._name = name;
this._age = age;
}
Use Properties to pass data to Form2 and Events to return the Saved Data:
Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 edit = new Form2();
edit.SaveEvent += new Form2.SaveEventHandler(edit_SaveEvent); //Add event handler
edit.name = People[this.listView1.SelectedItems[0].Index].Name;
edit.age = People[this.listView1.SelectedItems[0].Index].Age;
edit.ShowDialog(this);
}
void edit_SaveEvent(object sender, SaveEventArgs e)
{
//Do Your work here with e.newAge and e.newName
((Form2)sender).Close(); //Close Form2
}
Form2
public partial class Form2 : Form
{
public delegate void SaveEventHandler(object sender, SaveEventArgs e);
public event SaveEventHandler SaveEvent;
public string name { get; set; }
public string age { get; set; }
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = name;
textBox2.Text = age;
}
private void button1_Click(object sender, EventArgs e)
{
SaveEvent(this, new SaveEventArgs(textBox1.Text, textBox2.Text));
}
}
public class SaveEventArgs
{
public SaveEventArgs(string name, string age) {newName = name; newAge = age; }
public String newName {get; private set;} // readonly
public String newAge {get; private set;}
}
Use custom constructor for this
In Form 1
private void button1_Click(object sender, EventArgs e)
{
string name = People[this.listView1.SelectedItems[0].Index].Name;
int age = People[this.listView1.SelectedItems[0].Index].Age;
Form2 edit = new Form2(name,age);
edit.ShowDialog(this);
}
In Form 2
public form2(string name,int age)
{
textBox1.Text = name;
textBox2.Text = age.ToString();
}
Use oop concepts..It is nice.

Categories

Resources