passing gridview data between 2 forms - c#

how to tranfer Form1 checked GridView Rows Data on Form2 Gridview?
Like This:

There are lot of ways to achieve this. The simplest that comes in my mind is:
-Create an istance of GetDataForm and call a method which displays the form and get the result:
GetDataForm form2 = new GetDataForm();
List<DataGridViewRow> res = form2.ShowForm();
for (int i = 0; i < res.Count; i++)
mainFormGrid.Rows.Add(res[i]);
-In your GetDataForm you should have the following method:
bool _closedByTransferButton = false;
public List<DataGridViewRow> ShowForm()
{
ShowDialog();
List<DataGridViewRow> res = new List<DataGridViewRow>();
if(_closedByTransferButton)
{
for(int i = 0;i<grid.Rows.Count;i++)
if((bool)grid.Rows[i].Cells["checkboxColumn"].Value)
res.Add(grid.Rows[i]);
}
return res;
}
-And the Click event of your Transfer button should be:
private void tranferButton_Click(object sender, EventArgs e)
{
_closedByTransferButton = true;
Close();
}
Hope this helps.

Related

Using variables in primary Form from secondary From

I am having issues transfering data points from one form to another. I have made sure that the button inside of addTagsForm has a public modifier.
I've looked at multiple solutions of using data values from one form to another and I must be missing something from them.
Here is what I have in Form1:
//Inside Form1
XMLDocGen.PLCData PLC = new XMLDocGen.PLCData();
List<XMLDocGen.TagData> tags = new List<XMLDocGen.TagData>();
AddTagsForm addTagsForm = new AddTagsForm();
addMoreTagsSelected = addTagsForm.addMoreTagsEnabled;
if(addMoreTagsSelected)
{
for(int i= 0; i < 8; i++)
tags.Add(new XMLDocGen.TagData(addTagsForm.addTags[i], addTagsForm.addDataTypes[i], addTagsForm.addElemSizes[i], addTagsForm.addElemCounts[i]));
}
Here is what is inside of addTagsForm
public void button1_Click(object sender, EventArgs e)
{
addMoreTagsEnabled = true;
var tagNames = new List<TextBox>() { tagNameBoxAMT1, tagNameBoxAMT2, tagNameBoxAMT3, tagNameBoxAMT4, tagNameBoxAMT5, tagNameBoxAMT6, tagNameBoxAMT7, tagNameBoxAMT8 };
var dataTypes = new List<ComboBox>() { dataTypeBoxAMT1, dataTypeBoxAMT2, dataTypeBoxAMT3, dataTypeBoxAMT4, dataTypeBoxAMT5, dataTypeBoxAMT6, dataTypeBoxAMT7, dataTypeBoxAMT1 };
var elemSizes = new List<TextBox>() { elemSizeBoxAMT1, elemSizeBoxAMT2, elemSizeBoxAMT3, elemSizeBoxAMT4, elemSizeBoxAMT5, elemSizeBoxAMT6, elemSizeBoxAMT7, elemSizeBoxAMT8 };
var elemCounts = new List<TextBox>() { elemCountBoxAMT1, elemCountBoxAMT2, elemCountBoxAMT3, elemCountBoxAMT4, elemCountBoxAMT5, elemCountBoxAMT6, elemCountBoxAMT7, elemCountBoxAMT8 };
for (int i = 0; i < 8; i++)
{
addTags.Add(tagNames[i].Text);
addDataTypes.Add(dataTypes[i].Text);
addElemSizes.Add(elemSizes[i].Text);
addElemCounts.Add(elemCounts[i].Text);
}
this.Hide();
}
I have checked to make sure each list is populated correctly and they are. As well as the Lists being public. The problem is trying to grab these values from Form1. There has to be something simple that I'm missing! Thanks for the help!
With the reference of your comment i've generated an idea for you. By writing a simple public Action in your Second form Form2 you can achieve your goal. Below i'm showing an example:
Declare a public Action in your Form2 global scope with your desired collection type, like this way:
public Action<List<TextBox>, List<ComboBox>> actGetCollection;
Keep a method with some of your desired collection type parameter in your Form1 like this way:
private void GetCollectionItems(List<TextBox> addTags, List<ComboBox> addDataTypes)
{
//you will get your list items here and do whatever you want with these
}
In your Form1 from where your second form will open bind your GetCollectionItems() method with your Action in Form2 (assuming you do this in a button's click event) like this way:
private void button1_Click(object sender, EventArgs e)
{
//create an instance of your Form2 Form
Form2 obj = new Form2();
//bind your function with the action
obj.actGetCollection = GetCollectionItems;
//then call your Form2's ShowDialog() method to show the form
obj.ShowDialog();
//now your Form2 is opended
}
Now in your Form2's button_click event do this:
public void button1_Click(object sender, EventArgs e)
{
addMoreTagsEnabled = true;
var tagNames = new List<TextBox>() { tagNameBoxAMT1, tagNameBoxAMT2, tagNameBoxAMT3, tagNameBoxAMT4, tagNameBoxAMT5, tagNameBoxAMT6, tagNameBoxAMT7, tagNameBoxAMT8 };
var dataTypes = new List<ComboBox>() { dataTypeBoxAMT1, dataTypeBoxAMT2, dataTypeBoxAMT3, dataTypeBoxAMT4, dataTypeBoxAMT5, dataTypeBoxAMT6, dataTypeBoxAMT7, dataTypeBoxAMT1 };
var elemSizes = new List<TextBox>() { elemSizeBoxAMT1, elemSizeBoxAMT2, elemSizeBoxAMT3, elemSizeBoxAMT4, elemSizeBoxAMT5, elemSizeBoxAMT6, elemSizeBoxAMT7, elemSizeBoxAMT8 };
var elemCounts = new List<TextBox>() { elemCountBoxAMT1, elemCountBoxAMT2, elemCountBoxAMT3, elemCountBoxAMT4, elemCountBoxAMT5, elemCountBoxAMT6, elemCountBoxAMT7, elemCountBoxAMT8 };
for (int i = 0; i < 8; i++)
{
addTags.Add(tagNames[i].Text);
addDataTypes.Add(dataTypes[i].Text);
addElemSizes.Add(elemSizes[i].Text);
addElemCounts.Add(elemCounts[i].Text);
}
//call the action
if(actGetCollection != null)
actGetCollection(addTags, addDataTypes);
this.Hide();
}
When your Form2 wil disappear your code will get back to your Form1's event from where you're called your Form2. Now in your GetCollectionItems() you've the collection items that you're wanted.
You can set stuff in your second form from your first:
class Form1
{
...
public void OnButtonPress()
{
var anotherForm = new Form2();
anotherForm.AList = mylist;
anotherForm.BList = myBList;
anotherForm.ShowDialog();
}
}
Alternatively, you could create a class that encapsulates everything you want to pass between the two and so only pass on thing. If it's mandatory I would put it in Form2's constructor:
public Form2(MyImportantStuff stuff)

Populate textbox on different form from data in a datagridview

I'm trying to populate data from a DataGridView into TextBoxes which are on a different form. I can populate TextBoxes that are on the same form as the DataGridView. I'm not sure on how to reference the other form?
My code :
var value = dgvInfo.Rows[e.RowIndex].Cells["Description"].Value;
if (value != null)
{
txtDescription.Text = value.ToString();
}
EDIT 1:
The possible duplicate question deals with passing data from one TextBox to another. In my question it is passing data from a DataGridView to a TextBox.
Pass Value as constructor parameter to destination form (for example Form4):
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
Form4 fr = new Form4(dgvInfo.Rows[e.RowIndex].Cells["Description"].Value.ToString());
fr.ShowDialog();
}
And in the destination form:
public Form4(string p)
{
InitializeComponent();
txtDescription.Text = p;
}
To pass more than one value to another form you should use a List like this:
private void button1_Click(object sender, EventArgs e)
{
List<string> lst = new List<string>();
foreach (DataGridViewRow row in dgvInfo.SelectedRows)
{
var Value = row.Cells["Description"].Value.ToString();
if (!string.IsNullOrWhiteSpace(Value))
{
lst.Add(Value);
}
}
Form4 fr = new Form4(lst);
fr.ShowDialog();
}
And then in destination form:
public Form4(List<string> p)
{
InitializeComponent();
txtDescription.Text = p[0];
textBox1.Text = p[1];
}

print dynamically generated checkbox selected rows from datagridview to crystal report on another form c#

I have dynamically added checkboxes for each row in datagridview (form1)and i am trying to generate crystal report on a new form (form 2) for only those rows whose checkbox is checked.
My code on form1 button click is
private void btn_Print_Click(object sender, EventArgs e)
{
//im trying to insert selected rows in datatable which is datasource for crystal report
DataTable table = new DataTable();
int i = 1;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
//dataGridView1.SelectedRows[0].Cells["select"].Value)
{
for (int j = 1; j < dataGridView1.ColumnCount; ++j)
{
table.Rows[i][j] = row.Cells[j].Value;
}
++i;
}
if (cb_reptype.SelectedItem.ToString() == "Individual")
{
//here im specifying the path for new form2
string path = table.ToString();//dataGridView1.SelectedRows[1].Cells["table"].Value.ToString();
Form2 f2 = new Form2(path);
//ReportDocument crystal = new ReportDocument();
//crystal.Load(dataGridView1.SelectedRows[0].Cells["ReportPath"].Value.ToString());
//pass = crystal;
f2.Show();
}
and my code on form2 is
public partial class Form2 : Form
{
public string source;
public Form2(string path)
{
source = path;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.crystalReportViewer1.ReportSource = source;
}
}
on debugging the program and button click event , new form is opening but it is showing below error.
I have tried a lot of research on this topic but not upto the mark.
Kindly reply as soon as possible.. Thanks :)
Try providing valid document in Form constructor inside button click event.
Valid document could be .xml, .rpt file for generating crystal report.
For the current scenario do few additions:
if (cb_reptype.SelectedItem.ToString() == "Individual")
{
DataSet ds = new DataSet();
ds.Tables.Add(table);
ds.WriteXmlSchema("Drive:\\Somefolder\\Sample.xml"); // this generates Xml file.
Now pass this path to Form constructor as this is valid report file.
Form f2 = new Form("Drive:\\Somefolder\\Sample.xml");
f2.show();
}
You need to add rows to DataTable before adding any value from datagrid.
while(table.Rows.Count<dataGridView1.SelectedRows.Count)
{
table.Rows.Add();
}
Once done with this you can add values from datagrid:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
for (int j = 1; j < dataGridView1.ColumnCount; ++j)
{
table.Rows[i][j] = row.Cells[j].Value;
}
++i;
}
Hope it works.

displaying data from selected rows in datagridview into a textbox

Im trying to display data from datagridview into a textboxes of another form. The form 2 has textboxes. Here is my code:
private void btnAddOrder_Click(object sender, EventArgs e)
{
Add_Order addOrder = new Add_Order();
addOrder.
}
Im trying to type addOrder.textBox1.Text = dtgv_Items.SelectedRows[0].Cells[1].Value.ToString(); but textBox1 that should automatically appear is not displaying, meaning there's an error. How could I solve this? :)
Here is an example for any selected cell:
Form2:
private string pVal;
//getter and setter
public string PassVal
{
get { return pVal; }
set { pVal = value; }
}
//or event that you need
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = pVal;
}
Form1:
Form2 f2 = new Form2();
int selectedCellCount = dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
for (int i = 0; i < selectedCellCount; i++)
{
int column = dataGridView1.SelectedCells[i].ColumnIndex;
int row = dataGridView1.SelectedCells[i].RowIndex;
f2.PassVal = dataGridView1[column, row].Value.ToString();
}
}
f2.Show();
with this peace of code you'll get text from any selected cell in your textbox.
hope it helped you a little bit.
First, create getter and setter on the second form.
private string sampleData = string.Empty;
public string SampleData
{
get { return sampleData; }
set { value = sampleData; }
}
Then you can use this on your first form:
private void btnAddOrder_Click(object sender, EventArgs e)
{
Add_Order addOrder = new Add_Order();
addOrder.SampleData = dtgv_Items.SelectedRows[0].Cells[1].Value.ToString();
}
To view the result on your second form, use this:
this.TextBox1.Text = SampleData;
use the textbox it self direct
textBox1.Text = dtgv_Items.SelectedRows[0].Cells[1].Value.ToString();

Trying to grab information from a Data Table in Form 2 and set Textboxes in Form 1 using C#

I have two forms (Form 1 and Form 2), I am successful in passing a data table from Form 1 to Form 2 by filling a data grid view in a dialog box. I also have an event handler to capture double click events on a selected row. When the event occurs I want to set textboxes in form 1 from the click event in form 2. No matter what I try I can not seem to show the text inside the textboxes. Below is my code:
//Code begins here
//....Function to fill data table from form 1 and pass to form 2
private void buttonNewEntryLookUp_Click(object sender, EventArgs e)
{
try
{
cs.Open();
da.SelectCommand = new SqlCommand("Select ctx_customername AS Customer, ctx_contactname AS Contact, ctx_custaddress1 AS Address, ctx_custcity AS City, ctx_custstate AS State, nno_custzip AS ZIP, ctx_custemail AS Email FROM Customers WHERE nno_custphone = '" + maskedTextBoxNewLogTel.Text + "'", cs);
dt.Clear();
da.Fill(dt);
}
catch
{
MessageBox.Show("Connection to Database could not be established, please close this application and try again. If problem continues please contact server Admin. Thank you.", "AAMP");
//Display this message if connection could not be made
}
cs.Close();//close connection to db
if (dt.Rows.Count == 0)//if there are no returned results then this must be a new entry into the database
{
MessageBox.Show("Phone Number Not Found in Database.", "AAMP");
}
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
}
}
public void getContactInfo(string[] contactInfo)
{
textBoxNewLogCustomerName.Text = contactInfo[0];
textBoxNewLogContactName.Text = contactInfo[1];
textBoxNewLogAddress.Text = contactInfo[2];
textBoxNewLogCity.Text = contactInfo[3];
textBoxNewLogState.Text = contactInfo[4];
textBoxNewLogZIP.Text = contactInfo[5];
textBoxNewLogEmail.Text = contactInfo[6];
}
//code for form 2
public partial class Form2 : Form
{
/*Globals for Form 2*/
DataTable g_dt;
public Form2(DataTable dt)
{
InitializeComponent();
dataGridViewLookUp.DataSource = dt;
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Form1 form1 = new Form1();
string[] contactInfo = new string[7];
contactInfo[0] = Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]);
contactInfo[1] = Convert.ToString(g_dt.Rows[e.RowIndex]["Contact"]);
contactInfo[2] = Convert.ToString(g_dt.Rows[e.RowIndex]["Address"]);
contactInfo[3] = Convert.ToString(g_dt.Rows[e.RowIndex]["City"]);
contactInfo[4] = Convert.ToString(g_dt.Rows[e.RowIndex]["State"]);
contactInfo[5] = Convert.ToString(g_dt.Rows[e.RowIndex]["ZIP"]);
contactInfo[6] = Convert.ToString(g_dt.Rows[e.RowIndex]["Email"]);
form1.getContactInfo(contactInfo);//return the row number being clicked.
this.Close();
}
}
I am successful in passing the data table to form 2 and capturing the correct information to fill the string array but when I pass the string array back by calling the getContactInfo function I can not seem to set my textboxes with the data. Can someone please, please help!
Thanks.
Your OP is a little vague, but I have some code that does this, takes some data in form 2 and sends it back to form 1.
Here's the code from form1:
private void btnGroupNameLookup_Click(object sender, EventArgs e)
{
//instantiate an instance of the grp name lookup form
frmGroupNameLookup lookupName = new frmGroupNameLookup();
//add an event handler to update THIS form when the lookup
//form is updated. (This is when LookupUpdated fires
lookupName.GroupNamesFound += new frmGroupNameLookup.LookupHandler(lookupName_GroupNamesFound);
//rc.ReconCFUpdated += new ReconCaseFileChecklist.ReconCFListHandler(ReconCFForm_ButtonClicked);
lookupName.Show();
}
void lookupName_GroupNamesFound(object sender, GroupNameLookupUpdateEventArgs e)
{
//update the list boxes here
foreach (string s in e.Parents)
{
lstFilteredGroupParents.Items.Add(s);
}
foreach (string s in e.Groups)
{
lstFilteredGroups.Items.Add(s);
//link supgroups and plan ids
GetFilteredSubgroupNos(s);
GetFilteredPlanIds(s);
}
//ensure dupes are stripped out
//filter out duplicates
var noDupeSubgroups = subgroupList.Distinct().ToList();
noDupeSubgroups.Sort();
foreach (string s in noDupeSubgroups)
{
lstFilteredSubgroups.Items.Add(s);
}
var noDupePlanIDs = planIDList.Distinct().ToList();
noDupePlanIDs.Sort();
foreach (string s in noDupePlanIDs)
{
lstFilteredPlanID.Items.Add(s);
}
}
From Form2
public partial class frmGroupNameLookup : Form
{
//add a delegate, the GroupNameLookupUpdateEventArgs class is defined at the bottom
//of this file
public delegate void LookupHandler(object sender, GroupNameLookupUpdateEventArgs e);
//add an event of the delegate type
public event LookupHandler GroupNamesFound;
//this event closes the forms and passes 2 lists back to form 1
private void btnCommit_Click(object sender, EventArgs e)
{
List<string> prnt = new List<string>();
List<string> grp = new List<string>();
//get selected rows
if (grdLookup.SelectedRows.Count > 0)
{
foreach (DataGridViewRow row in grdLookup.SelectedRows)
{
prnt.Add(row.Cells[0].Value.ToString());
grp.Add(row.Cells[1].Value.ToString());
}
//filter out duplicates
var noDupeParentGroups = prnt.Distinct().ToList();
noDupeParentGroups.Sort();
// instance the event args and pass it each value
GroupNameLookupUpdateEventArgs args =
new GroupNameLookupUpdateEventArgs(noDupeParentGroups, grp);
// raise the event with the updated arguments
this.GroupNamesFound(this, args);
this.Dispose();
}
}
}
public class GroupNameLookupUpdateEventArgs : System.EventArgs
{
// add local member variables to hold text
private List<string> mParents = new List<string>();
private List<string> mGroups = new List<string>();
// class constructor
public GroupNameLookupUpdateEventArgs(List<string> sParents, List<string> sGroups)
{
this.mParents = sParents;
this.mGroups = sGroups;
}
// Properties - Viewable by each listener
public List<string> Parents
{
get { return mParents; }
}
public List<string> Groups
{
get { return mGroups; }
}
}
Simple. Make the contact information a method public in Form2 and then just assign it after the ShowDialog() in form1.
else//number was found
{
Form2 form2 = new Form2(dt);//create object of form 2 and pass the data table.
form2.ShowDialog();//show form 2 with data table in the grid view.
getContactInfo(form2.ContactInfoFromForm2);
}
You're passing the datatable into the constructor of Form2:
Form2 form2 = new Form2(dt);
You could instead pass a reference to the entire Form1:
Form2 form2 = new Form2(this);
Then you make public methods on Form1 that Form2 can use to update data. Something like this:
//In Form1
public DataTable getDataTable(){
//return datatable
}
public void setTextBoxValue(string Value){
//Set the value
}
And then in Form2
private Form1 _form1;
public Form2(Form1 form1){
_form1 = form1;
dataGridViewLookUp.DataSource = _form1.getDataTable();
g_dt = dt;
}
private void dataGridViewLookUp_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
_form1.setTextBoxValue(Convert.ToString(g_dt.Rows[e.RowIndex]["Customer"]));
//etc
}
Are you getting an error or is the data just not displaying. Maybe try a ToString() method behind each stringarray index in the getcontactinfo method. (i.e. contactInfo[0].ToString();)

Categories

Resources