How to compare new and previous value in combobox? - c#

i have datagridview and column in it,and type is combobox.Combobox value's are used from sql data base.In combobox "Status" i have 5 different item value's.What i want is that when i change item value from combobox and press "save" button ,i want to check which value was before this one(before save) and say:
private void m02BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
try
{
if (StatusTextBox.Text == "3" && // + want to ask here if previous statusTextBox.text was "1" then to execute lines down if not goes to 'else')
{
DialogResult mbox = MessageBox.Show("do you want to save today's date and time?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
datumOtvaranjaDateTimePicker.Focus();
if (mbox == DialogResult.Yes)
{
datumOtvaranjaDateTimePicker.Value = DateTime.Now;
}
Save();
Refresh();
}
else
{
MessageBox.Show("you cant do that!!!" + Environment.NewLine + "Check what you typed and try again", "Upozorenje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Refresh();
}
}
catch (Exception)
{
}
}

Look at this other answer
You can handle the ComboBox.Enter event. Then save off the
SelectedItem or SelectedValue to a member variable
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Enter += comboBox1_Enter;
}
private void comboBox1_Enter(object sender, EventArgs e)
{
m_cb1PrevVal = comboBox1.SelectedValue;
}
private void RestoreOldValue()
{
comboBox1.SelectedValue = m_cb1PrevVal;
}
}

Related

label.Text = ComboBox.SelectedText(); always null?

I am making an application that has some options in drop-down menus that get populated from the App.Config file. I was testing a reset function when the program stopped doing the reset. My code for Form1 is below:
public Form1()
{
InitializeComponent();
InitializeDropDownMenu();
}
private void InitializeDropDownMenu()
{
//Populate all the menus from app.config
foreach (string s in Properties.Settings.Default.Box1Contents)
{
comboBox1.Items.Add(s);
}
foreach (string s in Properties.Settings.Default.Box2Contents)
{
comboBox2.Items.Add(s);
}
foreach (string s in Properties.Settings.Default.Box3Contents)
{
comboBox3.Items.Add(s);
}
//Controls for drop down menus
this.Controls.Add(comboBox1);
comboBox1.SelectedIndexChanged +=
new System.EventHandler(comboBox1_SelectedIndexChanged);
this.Controls.Add(comboBox2);
comboBox2.SelectedIndexChanged +=
new System.EventHandler(comboBox2_SelectedIndexChanged);
this.Controls.Add(comboBox3);
comboBox3.SelectedIndexChanged +=
new System.EventHandler(comboBox3_SelectedIndexChanged);
//Begin Program with all dDMenus enabled.
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
}
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox1.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox1.SelectedText;
}
else if( result == DialogResult.No)
{
comboBox1.ResetText();
}
}
private void comboBox2_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox2.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox2.SelectedText;
}
else if (result == DialogResult.No)
{
comboBox2.ResetText();
}
}
private void comboBox3_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox3.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox3.SelectedText;
}
else if (result == DialogResult.No)
{
comboBox3.ResetText();
}
}
private void ResetApp()
{
comboBox1.ResetText();
comboBox2.ResetText();
comboBox3.ResetText();
}
private void button1_Click(object sender, EventArgs e)
{
ResetApp();
label3.Text = "ResetApp Ran";
}
Any ideas as to why label3 is always set to null, and why when reset is clicked the ComboBoxes aren't being reset to blanks anymore?
Thank you for your help,
-Arthur
EDIT* I will use Items.Clear(); and then just call InitializeDropDownMenu() in the reset function. Should work for my intended use. Thank you all.
I think the problem is in use of SelectedText. The SelectedTextproperty "Gets or sets the text that is selected in the editable portion of a System.Windows.Forms.ComboBox".
Instead try to use the SelectedItem property.
label1.Text = comboBox1.SelectedItem.ToString();

Howto edit selected row but save as new row (textBox, DataGridView, SQL)

Im totaly new to coding but im trying to learn:)
In the application Im working on I have a button that adds a new row
Edit(true);
dbDocSet.DocData.AddDocDataRow(dbDocSet.DocData.NewDocDataRow());
docDataBindingSource.MoveLast();
and then I save from textboxes with another button
Edit(false);
docDataBindingSource.EndEdit();
docDataTableAdapter.Update(dbDocSet.DocData);
dataGridView1.Refresh();
I can also edit a row
Edit(true);
How can I edit a row but after edit save it to a new row instead of overwriting the one im editing?
Or, maybe I shold change it to work like this:
Instead of
- Add new row with newbutton
- Fill in textboxes
- Save with savebutton
Do like this:
- Fill in textboxes
- Save to new row with savebutton
Edit:
- Populate textboxes by selecting a row
- Make changes in textboxes
- Save to same row with changebuttonenter image description here
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Rectangle resolutionRect = System.Windows.Forms.Screen.FromControl(this).Bounds;
if (this.Width >= resolutionRect.Width || this.Height >= resolutionRect.Height)
{
this.WindowState = FormWindowState.Maximized;
}
this.docDataTableAdapter.Fill(this.dbDocSet.DocData);
Edit(false);
}
private void Edit(bool value)
{
textBox1.Enabled = value;
textBox2.Enabled = value;
textBox3.Enabled = value;
And then more textBox.Enable = value (143 st)
private void button1_Click(object sender, EventArgs e)
{ //-----Nytt dokument-----
try
{
Edit(true);
dbDocSet.DocData.AddDocDataRow(dbDocSet.DocData.NewDocDataRow());
docDataBindingSource.MoveLast();
textBox1.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
dbDocSet.DocData.RejectChanges();
}
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "" || dataGridView1.Rows[i].Cells[1].Value.ToString() == "")
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
}
}
private void button3_Click(object sender, EventArgs e)
{ //-----Öppna upp för att kunna ändra-----
Edit(true);
textBox1.Focus();
}
private void button4_Click(object sender, EventArgs e)
{ //-----Avbryt ifyllnad dokument-----
Edit(false);
docDataBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{ //-----Spara dokument-----
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
MessageBox.Show("Dokumenttyp måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
}
else
if (string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("Dokumentnamn måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox2.Focus();
}
else
if (string.IsNullOrWhiteSpace(textBox3.Text))
{
MessageBox.Show("Revision för dokumentet måste anges !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox3.Focus();
}
else
try
{
Edit(false);
docDataBindingSource.EndEdit();
docDataTableAdapter.Update(dbDocSet.DocData);
dataGridView1.Refresh();
textBox1.Focus();
MessageBox.Show("Dokument sparat med lyckat resultat !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
dbDocSet.DocData.RejectChanges();
}
}
private void dataGridView1_KeyDown_1(object sender, KeyEventArgs e)
{ //-----Ta bort valt dokument-----
if (e.KeyCode == Keys.Delete)
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
if (MessageBox.Show("Är du säker på att du vill ta bort dokumentet ?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
Try using dataGridView1_CellValidating - LINK. It occurs when a cell loses input focus, enabling content validation. So when validating if you want to add new row instead of editing current one, just get current values from row and use it to add new row, and at the end of validating use e.Cancel to cancel row edit.
If you want to copy data from some row to textboxes, make changes in textboxes and then with button add new row you can use dataGridView1_CellClick - LINK. So basically when user click cell, you get that row index of that cell, and then with that you can access every cell of that row. With that you populate textboxes, make some changes, and on save button you just add new row.
If your question is also how to add new row to datagridview you have answer here: LINK

How to Require Confirmation on Form Close When there is Changed Data in a DataGridView

I have simple Form1 with datagridview and I've enabled editing and adding.
Now, when I click on closing form button, and if some of existing cell values are changed or new row has been added I want dialogue box to open (for example, asking me if I want to save changes or don't), and if there is no changes , just to perform simple form closing.
How can I accomplish this ?
Ok, here is what I've got so far.
I'm trying to this one using CSLA framework, I've created root editable collection public class PDVCollection : BusinessBindingListBase<PDVCollection, PDV> and editable child public class PDV : BusinessBase<PDV>
On Form1 I've got this code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public PDVCollection s;
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1.DataSource = PDVCollection.GetAll();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
bindingSource1.DataSource = s;
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex > -1)
{
PDV sel = (PDV)dataGridView1.CurrentRow.DataBoundItem;
s = (PDVCollection)bindingSource1.DataSource;
s.Remove(sel);
s = s.Save();
}
}
i want to cut s = s.Save(); from both toolStripButton1_Click and toolStripButton3_Click and If something is changed/added/deleted and I perform closing event
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (//some code to implement)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
If you're doing databinding to a DataSource, then you can use the datasource to determine whether it has been changed in the FormClosing or FormClosed event. The actual implementation would be up to the type of datasource you are using.
If you're not specifying a datasource, then the data by default can be accessed in the Rows collection of the DataGrid. That collection class doesn't have a "changed" flag by default, but it DOES have a CollectionChanged event that you could hook up.
So, in your form's construtor, you could do a
DataGrid1.CollectionChanged += Rows_CollectionChanged;
And then in your Rows_CollectionChanged you could set a flag that data has changed and needs to be saved. Obviously giving much more detail would require knowing more about the details of your datagrid and datasource.
Per the comments below, you may want more than a flag depending on how you define "changed". If you need to know that a field was changed, then changed back to the original value then as a commenter below says a simple flag wouldn't do it, and you might need to store a shadow copy of the original data.
That said, if you need to handle really complicated undo scenarios you're going to want datasource designed for that, which is a whole different topic.
EDIT: If you're using CSLA objects as your data source, then there should be an IsDirty flag on the objects. So just iterate over the items in the datasource on the FormClosed event and check the IsDirty flag for each object.
You need to create flag variable and initially set it to false
bool isAnythingChange = false;
And make this variable to true on new row add, or value change event. For sample I have shown below
void txt_Change(object sender, EventArgs e)
{
isAnythingChange = true;
}
And while you are handling form closing event make point to check isAnythingChange. If it's value is true then ask for confirmation or else close form without confirmation.
EDIT:
As you maintain in your question, updated code may be like this.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (isAnythingChange)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
Ok, here is final working solution, if anyone is looking for it.
public Form1()
{
InitializeComponent();
}
public PDVCollection s;
private void Form1_Load(object sender, EventArgs e)
{
bindingSource1.DataSource = PDVCollection.GetAll();
s = (StopaPDVCollection)bindingSource1.DataSource;
}
private void toolStripButton1_Click(object sender, EventArgs e)
s = s.Save();
bindingSource1.DataSource = s;
}
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.RowIndex > -1)
{
PDV sel = (PDV)dataGridView1.CurrentRow.DataBoundItem;
s.Remove(sel);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (s.IsDirty)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save changes", "Message", "Poruka", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
s = (PDVCollection)bindingSource1.DataSource;
s = s.Save();
bindingSource1.DataSource = s;
}
else if (dialogResult == DialogResult.No)
{
this.DialogResult = DialogResult.OK;
}
}
}
}

how to loop through an entire datagrid in f1 and pass values as string to label in f2

i have a datagrid in say form1 with some records in it and form 2 as a registration form which shows as dialog to form1. now upon a new registration with form2 i need to check whether the client has already been registered or not with records in the datagrid and display a message saying client already exist. so far i've been successful in passing a selected row in form1 as string to compare what ever client name being entered in form2. now i would like to know how to loop through entire datagrid and pass them as values to a label in form2 to enhance my checking up. below is how i do passing from form1 to form2
form 1 string declaration
public string strlabel2
{
get { return txtboxClearingAgent.Text; }
}
this where txtboxClearingAgent is taken from
private void kryptonDataGridView1_Validated(object sender, EventArgs e)
{
txtboxClearingAgent.Text = kryptonDataGridView1.SelectedRows[0].Cells["Clearing Agent Name"].Value.ToString();
and passed to form2 through showdialog
private void kryptonButton1_Click_1(object sender, EventArgs e)
{
frmNewClient frmNewClient1 = new frmNewClient();
frmNewClient1._strData = strlabel2;
frmNewClient1.ShowDialog();
and received in form 2
public string _strData
{
set { lblDatagrid.Text = value; }
}
and if statement to check during insertion
if (lblDatagrid.Text == txtboxClientName.Text)
{
MessageBox.Show("Client exist", "Checking Client(s) List", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else if (lblDatagrid.Text != txtboxClientName.Text)
{
DialogResult result = MessageBox.Show("Do you want to save this Entry?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
MessageBox.Show("New Client Entry has successfully been Saved", "Saving Client(s) Entry", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (result == DialogResult.No)
{
return;
}
int result1 = cmd.ExecuteNonQuery();
lblDat.Text = "1";
}

How to check in real time if data was enteder from one of the classes into a texbox?

My question comes from a problem which I have right now. I have MainWindow, AuthenticateWindow, and AddEntryWindow which all are WinForms. In main window I have possibility to Authenticate and Add Entry into my main windows textbox. They can not add an entry until they authenticate (no problem with this). I need to add an entry to the text box which will update my main windows textbox. The problem if, how can I check if entry was added to my textbox?
I am trying to have a Save option from menu strip. I am getting an error whenever I am trying to save an empty file. How could I authenticate the saving process by Save button by having it first disabled, and enabled after entry was added?
I could always verify if if textbox had an entry but I want to have button disabled first, and enabled after entry was added. I do not have a privilege to do so as of right now.
Please ask questions if I am not clear enough.
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
if (txtDisplay.Text != string.Empty)
{
sfdSaveToLocation.ShowDialog();
}
}
MainWindow.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
// Prohibit editing.
txtDisplay.Enabled = false;
}
public string ChangeTextBox
{
get
{
return this.txtDisplay.Text;
}
set
{
this.txtDisplay.Text = value;
}
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
private void tsmiClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
sfdSaveToLocation.ShowDialog();
}
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string theFileName = sfdSaveToLocation.FileName;
EncryptDecrypt en = new EncryptDecrypt();
string encrypted = en.Encrypt(txtDisplay.Text,
storedAuth.UserName, storedAuth.Password);
MessageBox.Show(encrypted);
File.WriteAllText(theFileName, encrypted);
}
}
}
AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
string user, pass;
// Initializind ArrayList to store all data needed to be added or retrived.
private ArrayList addedEntry = new ArrayList();
// Initializing MainWindow form.
MainWindow mainWindow;
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
public AddEntryWindow(MainWindow viaParameter, string user, string pass)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
}
private void AddEntryWindow_Load(object sender, EventArgs e)
{ }
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex == -1)
{
MessageBox.Show("Please select entry type!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Each field must be filled for specified type.
// Here we are checking if all fields were filled.
else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
{
MessageBox.Show("Please fill all the fields!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int totalEntries = 0;
if(cmbType.SelectedIndex == 0)
addedEntry.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
else if(cmbType.SelectedIndex == 1)
addedEntry.Add(new AddWebSite(cmbType.Text,
txtUserName.Text, txtPassword.Text, txtURL.Text));
else if(cmbType.SelectedIndex == 2)
addedEntry.Add(new AddSerialCode(cmbType.Text,
txtSoftwareName.Text, txtSerialCode.Text));
StringBuilder stringBuilder = new StringBuilder();
foreach (var list in addedEntry)
{
if (list is AddPC)
{
totalEntries++;
AddPC tmp = (AddPC)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
totalEntries++;
AddWebSite tmp = (AddWebSite)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
totalEntries++;
AddSerialCode tmp = (AddSerialCode)list;
stringBuilder.Append(tmp.ToString());
}
}
mainWindow.ChangeTextBox = stringBuilder.ToString();
mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";
// Clearing all fields.
ClearFields();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing the Add Entry Window form.
this.Close();
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
// Deciding which data must be entered depending on
// what type is selected from combo box.
// PC
if (cmbType.SelectedIndex == 0)
{}
// Web Site
else if (cmbType.SelectedIndex == 1)
{}
// Serial Code
else if (cmbType.SelectedIndex == 2)
{}
}
private void ClearFields()
{
// Clearing all fields to the default state.
}
}
}
Regards.
It sounds like you probably just want to subscribe to the TextChanged event, which will be fired whenever the text in the textbox changes.
I can't say I really followed everything that you're doing, but I think you should be fine to just enable or disable your Save button within that event handler.
EDIT: It's not really clear where all your different components live, but you want something like:
// Put this after the InitializeComponent() call in the constructor.
txtDisplay.TextChanged += HandleTextBoxTextChanged;
...
private void HandleTextBoxTextChanged(object sender, EventArgs e)
{
bool gotText = txtDisplay.Text.Length > 0;
menuSaveButton.Enabled = gotText;
}
I'd also strongly advise you not to use ArrayList but to use the generic List<T> type. The non-generic collections should almost never be used in new code.

Categories