How to pass data between forms? - c#

I am developing a desktop application in which I want to get information from user. If user selects particular radio button then I am opening a new form in popup in which I have placed checked list box. After selecting values from check box I want to access selected value in the previous form. Below are images that can clear idea.
When user click on radio button in "Enable conent type" (as highlighted in the screen) a new form in popup is open to select values from checked list box. After selecting desired value , press "Select" button from Select Content Type form.
Now the form will be hidden but I want to get the selected values in the form "Create Lists".
My code for Radio Button event is:
private void rdbEnableCtypeYes_CheckedChanged(object sender, EventArgs e)
{
if (rdbEnableCtypeYes.Checked)
{
lblSelectContentType.Visible = true;
frmSelectContentType selectContentType = new frmSelectContentType();
selectContentType.rootWebUrl = rootWebUrl;
selectContentType.MdiParent = this.MdiParent;
selectContentType.StartPosition = FormStartPosition.CenterScreen;
selectContentType.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
selectContentType.Show();
}
else
{
lblSelectContentType.Visible = false;
cmbContentType.Visible = false;
}
}
My code for form of Select content type is:
public string rootWebUrl = string.Empty;
XDocument contentTypeFile = XDocument.Load(FilePaths.ContentTypesFilePath);
private void frmSelectContentType_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(rootWebUrl))
{
if (contentTypeFile != null)
{
XElement xSiteCollection = contentTypeFile.Descendants(XmlElements.SiteCollection).Where(x => x.Attribute(XmlAttributes.Url).Value.Equals(rootWebUrl)).FirstOrDefault();
if (xSiteCollection != null)
{
IEnumerable<XElement> xContentTypes = xSiteCollection.Descendants(XmlElements.ContentType);
if (xContentTypes.OfType<XElement>().Count() > 0)
{
foreach (XElement xContentType in xContentTypes)
{
ComboboxItem item = new ComboboxItem();
item.Text = xContentType.Attribute(XmlAttributes.Name).Value;
item.Value = xContentType.Attribute(XmlAttributes.Id).Value;
lstContenType.Items.Add(item);
}
}
}
}
}
}
What should I do?

Try This.
Select Content Type Form
private List<string> _selectedItems = new List<String>();
public List<string> SelectedItem
{
get {return _selectedItems;}
}
private void btnSelect_Click(object sender, EventArgs e)
{
for(int i=0; i<lst.Items.Count;i++)
{
if (lstContenType.GetItemCheckState(i) == CheckState.Checked)
_selectedItems.Add(lst.Items[i].ToString());
}
this.Close();
}
Create List Form
private void rdoEnableCntType_Checked(object sender, EventArgs e)
{
if (rdoEnableCntType.Checked = true)
{
FrmConentType frm = new FrmConentType();
frm.ShowDialog();
List<string> list = frm.SelectedItems;
//Place your code to use selected items
}
}

You can pass data in the Constructor of FormB. For example:
//Default Constructor
public FormB()
{
InitializeComponent();
}
// Overloaded Constructor
public FormB(string parameter1, string parameter2, string parameter3)
{
InitializeComponent();
}
For example:
public FormB(bool RbuttonChecked)
{
InitializeComponent();
if(RbuttonChecked)
{
//Code
}
}
Invoke FormB from FormA like:
FormB obj=new FormB(Rbtn.checked); //Invoking the overloaded constructor
obj.Show();

You can defined a list in the main form to store items user selected in "Select Content Type" windows. When user have finished the window "Select Content Type", you add selected items to the variable.
In Form "Create List" class:
public List<ContentType> selectedContentTypes = new List<ContentType>();
When user press "Select" button in form "Select Content Type", add items to the variable:
// For each selected items in the listbxo {
frmCreateList.selectedContentTypes.Items.Add(itemId);
// }
If you can post your source code, it would be easier to help.

Related

DataGridView not loading data programmatically

I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)

Retrieving value from combo box selected item

I am using Windows Application.I Put some data as direct values in combo box.I defined var type to combo box.I put these combo box on form load.Now I want to retrieve the value of selected item on my button2_click event and I tried below code to retrieve it,but it giving me error of The name comboBox does not exist in current context.Can any one suggest me how to fix it.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
// Initialize combo box
var comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
//Add file in ListBox.
listBox1.Items.Add(file);
}
}
else
{
// listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
}
}
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}
comboBox was local variable in Form1 .ctor. You can't access it from another method
options:
1) access to the control by name
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
...
}
2) make it a private member of the form as controls normally are, if they are created in designer
ComboBox comboBox;
public Form1()
{
InitializeComponent();
// Initialize combo box
comboBox = new ComboBox() {...};
...
}
Currently the Combobox appears to be a local variable. Try to make it a global field variable and you should be able to access it.

C# how to pass value from form to form through datagridview?

i have form, it goes like this
that nomor tabungan is auto generate
the problem is, i want to get nomor nasabah value from different form, through the datagridview. take a look at the following picture
there's a button ambil to retrieve the nomor nasabah value, and pass them to nomor nasabah textbox.text
i have successfully to get the nomor_nasabah value from datagridview. it is shown like the following picture
how do i pass the value to the tambah tabungan . nomor nasabah textbox.text ?
i have set the textbox modifier into public so when i click the ambil button, the textbox is filled with the retrieved value automatically.
how do i do that ?
i did the following code, and idk why it doesn't work
here is the ambil button code
private void button2_Click(object sender, EventArgs e)
{
Tabungan.Tambah tambahtabungan = new Tabungan.Tambah();
//nomornya is the retrieved value
tambahtabungan.textBox2.Text = nomornya;
}
here is the cari button code, to show getCustomer form
private void button2_Click(object sender, EventArgs e)
{
if (getcustomer == null || getcustomer.IsDisposed)
{
getcustomer = new getNasabah();
getcustomer.Show();
}
}
You should try this.
first make a public property on getCustomer form like
public string nomornyaValue { get; set;}
and modify your ambil button click event like, and set this property to your datagrid value.
private void button2_Click(object sender, EventArgs e)
{
nomornyaValue = nomornya;
this.DialogResult = DialogResult.OK;
}
and on tambah tabungan button Cari click call getCustomer form like
private void Cari_Click(object sender, EventArgs e)
{
/*getCustomer getCustomerForm = new getCustomer();
if(getCustomerForm.ShowDialog() == DialogResult.OK)
{
textBox2.Text = getCustomerForm.nomornyaValue;
}*/
if (getcustomer == null || getcustomer.IsDisposed)
{
getcustomer = new getNasabah();
}
if(getcustomer.ShowDialog() == DialogResult.OK)
{
textBox2.Text = getcustomer.nomornyaValue;
}
}

Passing input data from one form to a label in another form

I have some labels on a form whose purpose is to hold values from the user input of another form, therefore, I need to set the label text programatically instead of with the properties window. I have done this but the problem is that the data does not seem to be passing to the other form. I tried running debug but the solution locks up on me and I have to shut it down from the task manager. I had a breakpoint set on the method that opens the second form. My thinking was that as the program stepped through the method I could see if the properties were being filled with the correct info. Unfortunately, instead of stepping through the method, it just opens up the form and locks up
I am hoping that maybe someone could take a look at my code and tell me where I am going wrong.
After the user inputs all of the data, he/she clicks a button which saves it to the database and displays a message asking the user to click another button to go to another form. This part works fine. Here is the event handler code for that action:
private void btnEnterNutritionInfo_Click(object sender, EventArgs e)
{
//call methods from NutritionBOL class to input calculated
//data into textboxes
this.txtRMR.Text = Convert.ToString(busObject.GetRMRdata(
busObject.BodyWeight));
this.txtDailyActivityBurn.Text = Convert.ToString(
busObject.GetDailyActivityBurnData(
busObject.RestingMetabolicRate));
this.txtEnergyAmount.Text = Convert.ToString(
busObject.GetEnergyAmount(
busObject.RestingMetabolicRate, busObject.DailyActivityBurn));
this.txtYourNutritionLevel.Text = busObject.GetNutritionLevel(
busObject.DailyEnergyAmount);
//convert text box data and assign to variables
busObject.BodyFatStart = double.Parse(this.txtBodyFatStart.Text);
busObject.BodyFatEndOfPhase1 = double.Parse(this.txtBodyFatEndOfPhase1.Text);
busObject.BodyFatEndOfPhase2 = double.Parse(this.txtbodyFatEndOfPhase2.Text);
busObject.BodyFatEndOfPhase3 = double.Parse(this.txtbodyFatEndOfPhase3.Text);
busObject.BodyWeight = double.Parse(this.txtBodyWeight.Text);
busObject.RestingMetabolicRate = double.Parse(this.txtRMR.Text);
busObject.DailyActivityBurn = double.Parse(this.txtDailyActivityBurn.Text);
busObject.DailyEnergyAmount = double.Parse(this.txtEnergyAmount.Text);
busObject.BodyFatStartNotes = this.txtStartNotes.Text;
busObject.BodyFatEndOfPhase1Notes = this.txtBodyFatEndOfPhase1Notes.Text;
busObject.BodyFatEndOfPhase2Notes = this.txtBodyFatEndOfPhase2Notes.Text;
busObject.BodyFatEndOfPhase3Notes = this.txtBodyFatEndOfPhase3Notes.Text;
busObject.NutritionLevel = this.txtYourNutritionLevel.Text;
//call method to save input data
busObject.SaveData();
//set visibility to true
txtRMR.Visible = true;
txtDailyActivityBurn.Visible = true;
txtEnergyAmount.Visible = true;
txtYourNutritionLevel.Visible = true;
lblYourNutritionLevel.Visible = true;
}
Once that is finished, the user clicks the button to go to the other form. At this point, the label data is supposed to be passed to the other form. The other form opens, but the label data isn't filled: Here is the event handler for that button click:
private void btnMeasurementData_Click(object sender, EventArgs e)
{
//assign text boxes to properties
this.BodyFatB4 = this.txtBodyFatStart.Text;
this.BodyWeightB4 = this.txtBodyWeight.Text;
this.BodyFatAfter = this.txtBodyFatEndOfPhase1.Text;
this.BodyWeightAfter = this.txtBodyWeight.Text;
//instantiate an object from the MeasurementsBOL to pass data
MeasurementsForm measurementsForm = new MeasurementsForm();
measurementsForm.BodyFatB4 = this.BodyFatB4;
measurementsForm.BodyWeightB4 = this.BodyWeightB4;
measurementsForm.BodyFatAfter = this.BodyFatAfter;
measurementsForm.BodyWeightAfter = this.BodyWeightAfter;
//StartDate data is just being passed through to the
//MeasurementsForm from the FitnessTest form
measurementsForm.StartDate = this.StartDate;
this.Hide();
//method call to open MeasurementsForm
busObject.GoToMeasurementsForm(this.StartDate, this.BodyFatB4,
this.BodyWeightB4, this.BodyFatAfter, this.BodyWeightAfter);
}
Here is the code for the method call to open the MeasurementsForm:
public void GoToMeasurementsForm(string startDate, string bodyFatB4,
string bodyWeightB4, string bodyFatAfter, string bodyWeightAfter)
{
MeasurementsForm f2;
//logic to decide what to do if an instance is not already instanitated
if (Application.OpenForms["MeasurementsForm"] == null)
{
f2 = new MeasurementsForm();
f2.StartDate = startDate;
f2.BodyFatB4 = bodyFatB4;
f2.BodyWeightB4 = bodyWeightB4;
f2.BodyFatAfter = bodyFatAfter;
f2.BodyWeightAfter = bodyWeightAfter;
f2.Name = "MeasurementsForm";
}
//logic to decide what to do if an instance is not already instantiated
else
{
f2 = Application.OpenForms["MeasurementsForm"] as MeasurementsForm;
f2.StartDate = startDate;
f2.BodyFatB4 = bodyFatB4;
f2.BodyWeightB4 = bodyWeightB4;
f2.BodyFatAfter = bodyFatAfter;
f2.BodyWeightAfter = bodyWeightAfter;
}
f2.Show();
}
This is the code for the form that opens when the button is clicked:
public partial class MeasurementsForm : Form
{
//declare variables
string bodyFatB4 = "",
bodyWeightB4 = "",
bodyFatAfter = "",
bodyWeightAfter = "",
startDate = "";
//instantiate object from MeasurementsBOL class
MeasurementsBOL busObject = new MeasurementsBOL();
//default constructor
public MeasurementsForm()
{
InitializeComponent();
busObject.InitializeConnection();
}
//properties for variables
public string BodyFatB4
{
get { return bodyFatB4; }
set { bodyFatB4 = value; }
}
public string BodyWeightB4
{
get { return bodyWeightB4; }
set { bodyWeightB4 = value; }
}
public string BodyFatAfter
{
get { return bodyFatAfter; }
set { bodyFatAfter = value; }
}
public string BodyWeightAfter
{
get { return bodyWeightAfter; }
set { bodyWeightAfter = value; }
}
public string StartDate
{
get { return startDate; }
set { startDate = value; }
}
private void Form1_Load(object sender, System.EventArgs e)
{
//pass text data from nutrition form to labels
this.lblBodyFatB4FromNutrition.Text = this.BodyFatB4;
this.lblWeightB4FromNutrition.Text = this.BodyWeightB4;
this.lblBodyFatAfterFromNutrition.Text = this.BodyFatAfter;
this.lblWeightAfterFromNutrition.Text = this.BodyWeightAfter;
}
//event handler for B4 input data
private void btnEnterMeasurementsB4_Click(object sender, EventArgs e)
{
//convert input data and assign to variables
busObject.BodyFatB4 = double.Parse(lblBodyFatB4FromNutrition.Text);
busObject.BodyWeightB4 = double.Parse(lblWeightB4FromNutrition.Text);
busObject.ChestMeasurementB4 = double.Parse(txtChestB4.Text);
busObject.WaistMeasurementB4 = double.Parse(txtWaistB4.Text);
busObject.HipsMeasurementB4 = double.Parse(txtHipsB4.Text);
busObject.RightThighB4 = double.Parse(txtRightThighB4.Text);
busObject.LeftThighB4 = double.Parse(txtLeftThighB4.Text);
busObject.RightArmB4 = double.Parse(txtRightArmB4.Text);
busObject.LeftArmB4 = double.Parse(txtLeftArmB4.Text);
//call method to save input data
busObject.SaveB4Data();
//clear text boxes of data
this.txtChestB4.Clear();
this.txtWaistB4.Clear();
this.txtHipsB4.Clear();
this.txtRightThighB4.Clear();
this.txtLeftThighB4.Clear();
this.txtRightArmB4.Clear();
this.txtLeftArmB4.Clear();
//close form
this.Close();
}
//event handler for after input data
private void btnEnterMeasurementsAfter_Click(object sender, EventArgs e)
{
//convert input data and assign to variables
busObject.BodyFatAfter = double.Parse(lblBodyFatAfterFromNutrition.Text);
busObject.BodyWeightAfter = double.Parse(lblWeightAfterFromNutrition.Text);
busObject.ChestMeasurementAfter = double.Parse(txtChestAfter.Text);
busObject.WaistMeasurementAfter = double.Parse(txtWaistAfter.Text);
busObject.HipMeasurementAfter = double.Parse(txtHipsAfter.Text);
busObject.RightThighAfter = double.Parse(txtRightThighAfter.Text);
busObject.LeftThighAfter = double.Parse(txtLeftThighAfter.Text);
busObject.RightArmAfter = double.Parse(txtRightArmAfter.Text);
busObject.LeftArmAfter = double.Parse(txtLeftArmAfter.Text);
//call method to save input data
busObject.SaveAfterData();
//clear text boxes of data
this.txtChestAfter.Clear();
this.txtWaistAfter.Clear();
this.txtHipsAfter.Clear();
this.txtRightThighAfter.Clear();
this.txtLeftThighAfter.Clear();
this.txtRightArmAfter.Clear();
this.txtLeftArmAfter.Clear();
//close form
this.Close();
}
//event handler to open schedule form and hide this form
private void btnClickForSchedule_Click(object sender, EventArgs e)
{
this.Hide();
busObject.BackToMainSchedule(this.StartDate);
}
}

ListView selectedindexchanged

I need help to get a response when I click on an "Item" from a list view. Know that there is selectedindexchanged, but when I try to display a MessageBox so nothing happens, have tried lots of other things but have not managed to come up with something.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
...
while (reader.Read())
{
string alio = reader["fornamn"].ToString();
string efternamn = reader["efternamn"].ToString();
ListViewItem lvi = new ListViewItem(alio);
listView1.Items.Add(lvi);
lvi.SubItems.Add(efternamn);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
Assuming that 81.private void listView1_SelectedIndexChanged is properly linked to the listview, you will need to query the listview to find out what's selected:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.listView1.SelectedItems.Count == 0)
return;
string namn = this.listView1.SelectedItems[0].Text;
// Create the sql statement to retrieve details for the user
string sql = string.Format("select * from kunder where fornamn = '{0}', namn);
// do the same as you do to create a reader and update the controls.
}
Going by the term "when I try to display a MessageBox so nothing happens"\, I assume that you simply put MessageBox.Show("blah"); inside the event handler and never got it shown.
If that's the case, your event handler is not hooked properly to your form's list view. go back and see the text listView1_SelectedIndexChanged is anywhere to be found inside your Form1.Designer.cs file.
If not (or anyway), start over on a new form. That's the easiest way out. :)
private void lstView_KQ_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstView_KQ.SelectedItems.Count > 0)
{
ListViewItem itiem = stView_KQ.SelectedItems[lstView_KQ.SelectedItems.Count - 1];
if (itiem != null)
foreach (ListViewItem lv in lstView_KQ.SelectedItems)
{
txtMaNV.Text = lv.SubItems[0].Text;
cmbCV.Text = lv.SubItems[1].Text;
txtHoNV.Text = lv.SubItems[2].Text;
txtTenNV.Text = lv.SubItems[3].Text;
txtNgaysinh.Text = lv.SubItems[4].Text;
txtGioiTinh.Text = lv.SubItems[5].Text;
txtDiaChi.Text = lv.SubItems[6].Text;
txtSDT.Text = lv.SubItems[7].Text;
txtCMND.Text = lv.SubItems[8].Text;
}
}
}

Categories