c# Populating a ListView from an XML File - c#

I am still learning my way around c# and am trying to populate my ListView from an XML file.
Below is a picture of my ListView:
ListView
When I click a button on my UI, it reads the XML file using this code (Configuration.cs) here:
public static void LoadConfiguration(MainUI UIForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
MainUI uI = new MainUI();
UIForm.addItemsToActionsListView(doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_X").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Position_Y").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("RGB").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Is_Colour").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Target").Value, doc.Element("UABA").Element("Configure_Tab").Element("Actions_List").Element("ListItem_1").Attribute("Press_Button").Value);
}
Then it calls a method in my MainUI.cs and passes the relevant information I need to it.
public partial class MainUI : Form
{
public MainUI()
{
InitializeComponent();
}
private void MainUI_FormClosing(object sender, FormClosingEventArgs e)
{
Program._bMustShutdown = true;
}
public void NewActionsConsoleMessage(string Input)
{
ActionsConsole.Items.Add(DateTime.Now.ToString("h:mm:ss tt") + ": " + Input);
ActionsConsole.SelectedIndex = (ActionsConsole.Items.Count - 1);
}
private void btnAddAction_Click(object sender, EventArgs e)
{
if (txtboxLocationX.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position X and try again.");
MessageBox.Show("Enter a value for Position X and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxLocationY.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Position Y and try again.");
MessageBox.Show("Enter a value for Position Y and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxColourRGB.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Pixel RGB and try again.");
MessageBox.Show("Enter a value for Pixel RGB and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!radionbtnIsColour.Checked && !radionbtnIsNotColour.Checked)
{
NewActionsConsoleMessage("ERROR: Select either tracking by colour or tracking my not colour and try again.");
MessageBox.Show("Select either tracking by colour or tracking my not colour and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (cboxTarget.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Select a target and try again.");
MessageBox.Show("Select a target and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtboxActionBtn.Text.Length == 0)
{
NewActionsConsoleMessage("ERROR: Enter a value for Action to Take Button Press and try again.");
MessageBox.Show("Enter a value for Action to Take Button Press and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
ListViewItem addActionsItem = new ListViewItem(txtboxLocationX.Text);
addActionsItem.SubItems.Add(txtboxLocationY.Text);
addActionsItem.SubItems.Add(txtboxColourRGB.Text);
addActionsItem.SubItems.Add(radionbtnIsColour.Checked.ToString());
addActionsItem.SubItems.Add(cboxTarget.Text);
addActionsItem.SubItems.Add(txtboxActionBtn.Text);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSetPixelLocationColour_Click(object sender, EventArgs e)
{
var pixelColourPickerUI = new PixelColourPickerUI();
pixelColourPickerUI.ShowDialog();
txtboxLocationX.Text = pixelColourPickerUI._SelectedPixelMouseLocX;
txtboxLocationY.Text = pixelColourPickerUI._SelectedPixelMouseLocY;
txtboxColourRGB.Text = pixelColourPickerUI._SelectedPixelColor_R + "," + pixelColourPickerUI._SelectedPixelColor_G + "," + pixelColourPickerUI._SelectedPixelColor_B;
pnlConfigurePixelColour.BackColor = Color.FromArgb(pixelColourPickerUI._SelectedPixelColor_A, pixelColourPickerUI._SelectedPixelColor_R, pixelColourPickerUI._SelectedPixelColor_G, pixelColourPickerUI._SelectedPixelColor_B);
}
public ListView.ListViewItemCollection listViewItemCollection
{
get { return lvActionsList.Items; }
}
public void addItemsToActionsListView(string _LocX, string _LocY, string _RGB, string _IsColour, string _Target, string _ButtonPress)
{
Debug.WriteLine("_LocX: " + _LocX + "_LocY" + _LocY + "_RGB" + _RGB + "_IsColour" + _IsColour + "_Target" + _Target + "_ButtonPress" + _ButtonPress);
ListViewItem addActionsItem = new ListViewItem(_LocX);
addActionsItem.SubItems.Add(_LocY);
addActionsItem.SubItems.Add(_RGB);
addActionsItem.SubItems.Add(_IsColour);
addActionsItem.SubItems.Add(_Target);
addActionsItem.SubItems.Add(_ButtonPress);
Debug.WriteLine("Count: " + addActionsItem.SubItems.Count);
lvActionsList.Items.Add(addActionsItem);
}
private void btnSaveActionsList_Click(object sender, EventArgs e)
{
Configuration.Configuration.SaveConfiguration(items: lvActionsList.Items);
}
private void btnLoadProfile_Click(object sender, EventArgs e)
{
Configuration.Configuration.LoadConfiguration(this);
}
}
The first Debug.WriteLine returns the proper passed variables from Configuration.cs and the second Debug.WriteLine returns the proper count of 6 SubItems.
However, when viewing my ListView, it is still empty. Previously, I was able to add the the ListView using identical code (with different variables) when I was making what eventually became the XML file information. What am I doing wrong when trying to load the information from the XML? Do you need to see more code?
Thanks in advance!

Pass in the MainUI as argument to your static method:
public static void LoadConfiguration(MainUI UiForm)
{
XDocument doc = XDocument.Load("E:\\InnerSpace" + "\\Scripts\\BJScripts\\MySettings.xml");
UiForm.addItemsToActionsListView(doc.Element("UABA" etc
}

Related

retain previous value of text box till the form is closed

I am very new to c# , and learning to make data entry application,
in my entry form when the user clicks save all the data text boxes are refreshed and saved to database and the text box appears empty to enter gain. This is a continuous process.
Now i want my textbox1 to retain the same value where the user first entered till the form is closed.
Please help me how to achieve this?
i tried this code but the textbox is still empty:
private string value;
private void materiaNumberTextBox_TextChanged(object sender, EventArgs e)
{
var oldValue = value;
value = ((TextBox)sender).Text; // text1.Text
}
here's the code that does while saving:
private void btnsave_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Save?";
String caption = "Save Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
generateautoID();
this.iP_SpoolsBindingSource.EndEdit();
MessageBox.Show("The Record saved Successfully:" + outputSpoolNoTextBox.Text, "Save_Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsTableAdapter.Update(this.pINQCDataSet.IP_Spools);
this.iP_SpoolsTableAdapter.Fill(this.pINQCDataSet.IP_Spools);
//MessageBox.Show("The Record saved Successfully:", "Save_Update",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsBindingSource.AddNew();
string strStartenddateformat = "dd-MM-yyyy";
materialTypeComboBox.ValueMember = "Tungsten";
unitComboBox.ValueMember = "Mic";
statusComboBox.ValueMember = "Accepted";
cFComboBox.ValueMember = "";
bowOutOfComboBox.ValueMember = "";
ductilityOutofComboBox.ValueMember = "";
finishUOMComboBox.ValueMember = "Mic";
finishTypeComboBox.ValueMember = "Clean";
rejectReason1ComboBox.ValueMember = "";
rejectReason2ComboBox.ValueMember = "";
rejectReason3ComboBox.ValueMember = "";
lotNoTextBox.Text = "0";
dOEDateTimePicker.Format = DateTimePickerFormat.Custom;
dOEDateTimePicker.CustomFormat = strStartenddateformat;
dOEDateTimePicker.Value = DateTime.Now;
dOPDateTimePicker.Format = DateTimePickerFormat.Custom;
dOPDateTimePicker.CustomFormat = strStartenddateformat;
dOPDateTimePicker.Value = DateTime.Now;
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
here's the image of my form:
You can try the following code to save the first input text in the textbox.
Please use the event textbox_Leave event.
private void button1_Click(object sender, EventArgs e)
{
//Update the database
MessageBox.Show("Update success");
textBox1.Text = textbox; // return to the first input in the textbox
}
int i = 0;
string textbox = "";
private void textBox1_Leave(object sender, EventArgs e)
{
if (i == 0)
{
textbox = textBox1.Text;
i++;
}
}
Result:
Use a data reader to get the values from database and then populate values in textbox using those values.

Retrieve data datagrid to form

I have created a form to insert data. When data inserted it shows into datagridview1. I use dataGridView1_MouseClick event to retrieve data into the form. I successfully retrieved textbox data only into my form. I want to retrieve checkbox value which is checked or not. How can i retrieve checkbox value by clicking dataGridView1_MouseClick event.
I use following code for that:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Name.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
My result is here
But I want like this:
U can retrive values of other fields in similar like u did
This is for WPF control Checkbox link
I assume checkbox name of movie is movie_chbox
movie_chbox.IsChecked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Similarly you can do same for other too.
This is for winforms control Checkbox link
movie_chbox.Checked =
dataGridView1.SelectedRows[0].Cells[3].Value.toString() == "1" ?true:false
Instead of displaying 0 or 1 in datagridview display "Interested"/"Not Interested" and when you insert/update to database that time insert/update as 0 or 1 for better database mentainance.
Use the checked property of the check box control in your code and change the code for different categories. In your case the final code will be be something like below:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
string isCheckedMovie = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
string isCheckedSports = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
string isCheckedReading = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
string isCheckedWriting = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
if (isCheckedMovie == "1")
movieBox.Checked = true;
else
movieBox.Checked = false;
if (isCheckedSports == "1")
sportsBox.Checked = true;
else
sportsBox.Checked = false;
if (isCheckedReading == "1")
readingBox.Checked = true;
else
readingBox.Checked = false;
if (isCheckedWriting == "1")
writingBox.Checked = true;
else
writingBox.Checked = false;
}
catch (ApplicationException ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

using a try catch statement to keep a text box cleared

I am making a windows form application that takes various game entries (title,genre,price) and then stores them in an array with a maximum of four entries.
The error I am having is that if there are no values entered in my text boxes, I want a message box to appear to force the user to enter values. This happens.
The problem is that after this, it does not give the user another try. It just stops the program. I have tried using a try catch statement to do this but I am not quite sure how to use this. Would this be the correct solution?
namespace gameForm
{
public partial class gameEntryForm : Form
{
public gameEntryForm()
{
InitializeComponent();
}
struct Game
{
public string Title;
public string Genre;
public decimal Price;
}
static Game[] aNewGame = new Game[4]; //max size of the array is 4
static int newGameEntryIndex = 1;
private void gameEntryForm_Load(object sender, EventArgs e)
{
aNewGame[0].Title = "golf tour"; //this is a game already stored in the database
aNewGame[0].Genre = "sports";
aNewGame[0].Price = 1.99m;
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
}
//catch()
//{
//}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
private void btnShow_Click(object sender, EventArgs e)
{
rtbShow.Text = "Game Details \n\nGame 1 \n" + aNewGame[0].Title + "\n" + aNewGame[0].Genre + "\n" + aNewGame[0].Price + "\n\n" + "Game 2 \n" + aNewGame[1].Title + "\n" + aNewGame[1].Genre + "\n" + aNewGame[1].Price + "\n\n" + "Game 3 \n" + aNewGame[2].Title + "\n" + aNewGame[2].Genre + "\n" + aNewGame[2].Price + "\n\n" + "Game 4 \n" + aNewGame[3].Title + "\n" + aNewGame[3].Genre + "\n" + aNewGame[3].Price; ;
}
//clears the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
rtbShow.Clear();
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Add a return, no try/catch required:
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
return; // Exit current function
}
Try/catch is for when you have exceptions.
Try-Catch is of no use to you.
What you should do is in the btnSave_Click method return when the textboxes are not populated:
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text)
{
MessageBox.Show("Please enter a game genre, game title and game price.");
return;
}
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
...
There is another solution you could do. Only activate the Save-button if all three textboxes has values in them.
Something like:
private void ValidateGameData(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(tbGenre.Text) ||
String.IsNullOrWhiteSpace(tbTitle.Text) ||
String.IsNullOrWhiteSpace(tbPrice.Text))
{
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
tbGenre.TextChanged += ValidateGameData;
tbTitle.TextChanged += ValidateGameData;
tbPrice.TextChanged += ValidateGameData;
In your code for btnSave_Click you are testing the value of the various TextBoxes and displaying a message if they are NULL or empty.
However, you continue execution of your code even if they are NULL or empty.
You should stop processing more code if the conditions fail so that you don't try to use the NULL\empty values.
Something like:
private void btnSave_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tbGenre.Text))
{
MessageBox.Show("please enter a Game genre.");
}
else if (String.IsNullOrEmpty(tbTitle.Text))
{
MessageBox.Show("please enter a Game title");
}
else if (String.IsNullOrEmpty(tbPrice.Text))
{
MessageBox.Show("please enter a Game price");
}
else
{
// You forgot to create the new game at this index
aNewGame[newGameEntryIndex] = new Game();
aNewGame[newGameEntryIndex].Title = tbTitle.Text;
aNewGame[newGameEntryIndex].Genre = tbGenre.Text;
aNewGame[newGameEntryIndex].Price = Convert.ToDecimal(tbPrice.Text);
newGameEntryIndex++;
MessageBox.Show("entry saved");
//clears the text boxes
tbTitle.Clear();
tbGenre.Clear();
tbPrice.Clear();
}
}
I've also added a line:
aNewGame[newGameEntryIndex] = new Game();
As I couldn't see anywhere that you created the new Game object before trying to set it's properties.

I need to search an Object Array I created for a specific user-generated input and return one of the contents of the same element containing the input

I made a class I named DictionarySample to represent the fact that the procedures within this class are supposed to replicate several similar Dicitionary functionalities
public class DictionarySample
{
public int idNumb {get; set;}
public string fn { get; set; }
public string ln { get; set; }
public string adr { get; set; }
public string bday { get; set; }
public int num { get; set; }
}
via an array which I have initiated in the form class.
namespace Project
{
public partial class Form1 : Form
{
public int lastElementIndex = 0;
DictionarySample[] database = new DictionarySample[1000];
PriorityQueueSample[] line = new PriorityQueueSample[1000];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void buttonApply_Click(object sender, EventArgs e)
{
bool digitCharactersInfirst = textBoxFirstName.Text.Any(char.IsDigit);
bool digitCharactersInlast = textBoxLastName.Text.Any(char.IsDigit);
if (String.IsNullOrEmpty(textBoxIDNumber.Text))
{
MessageBox.Show("Enter an ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (int.Parse(textBoxIDNumber.Text) < 100000 || int.Parse(textBoxIDNumber.Text) > 999999)
{
MessageBox.Show("Invalid ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (String.IsNullOrEmpty(textBoxFirstName.Text))
{
MessageBox.Show("Enter First Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (digitCharactersInfirst == true)
{
MessageBox.Show("First Name can't contain digits. Please re-enter Given Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
textBoxFirstName.Text = String.Empty;
}
else if (String.IsNullOrEmpty(textBoxLastName.Text))
{
MessageBox.Show("Enter Last Name.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (digitCharactersInlast == true)
{
MessageBox.Show("Last Name can't contain digits. Please re-enter Surname.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
textBoxLastName.Text = String.Empty;
}
else if (String.IsNullOrEmpty(textBoxAdr.Text))
{
MessageBox.Show("Enter Address.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (String.IsNullOrEmpty(textBoxBirthday.Text))
{
MessageBox.Show("Enter Date of Birth.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
string c = "Proceed with the following Account Information? \n" + textBoxFirstName.Text + " " + textBoxLastName.Text + "," + textBoxIDNumber.Text + "\nAddress: " + textBoxAdr.Text + "\nBirthday: " + textBoxBirthday.Text;
DialogResult dialogResult = MessageBox.Show(c, "Verify information", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
int a = int.Parse(textBoxIDNumber.Text);
lastElementIndex++;
DictionarySample d = new DictionarySample();
d.idNumb = a;
d.fn = textBoxFirstName.Text;
d.ln = textBoxLastName.Text;
d.adr = textBoxAdr.Text;
d.bday = textBoxBirthday.Text;
d.num = lastElementIndex;
database[lastElementIndex] = d;
textBoxIDNumber.Text = String.Empty;
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
textBoxAdr.Text = String.Empty;
textBoxBirthday.Text = String.Empty;
string prio = "You may now Line-Up.\nYour priority number is:\t" + lastElementIndex;
MessageBox.Show(prio, "Take Note", MessageBoxButtons.OK);
}
else if (dialogResult == DialogResult.No)
{
}
}
The program goes like this: It asks the user for an IDNumber, Name, Address, and Birthday, then internally generates a priority number based on their order of application, which upon the click of the "Apply" button stores the User Info in my array named database.
*Check out a screen capture of form at http://tinypic.com/r/vfgkyh/8
After the user has applied, he then has to input his ID Number in the second panel which upon the click of the Line-Up button must look for the ID Number in the database and return the corresponding priority number, which will then both be inserted into another array with the functionalities of a Priority Queue.
My current code for the click of this Line-Up button goes as follows
private void buttonLineUp_Click(object sender, EventArgs e)
{
int temp = int.Parse(textBoxIDLINE.Text);
if (String.IsNullOrEmpty(textBoxIDLINE.Text))
{
MessageBox.Show("Enter an ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else if (int.Parse(textBoxIDLINE.Text) < 100000 || int.Parse(textBoxIDLINE.Text) > 999999)
{
MessageBox.Show("Invalid ID Number.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
else
{
for (int looper = 0; looper < 500; looper++)
{
//if (d.idNumb.database[looper] == int.Parse(textBoxIDNumber.Text))
//{
//}
//int idnb = 0;
//int priorityk = 0;
foreach (DictionarySample d in database)
{
if (d.idNumb == int.Parse(textBoxIDNumber.Text))
{
PriorityQueueSample lin = new PriorityQueueSample();
lin.idNumber = d.idNumb;
lin.pnumb = d.num;
labeldisplay.Text = d.idNumb + "," + d.num;
}
}
}
}
I haven't started inputting the data into the priorityqueue array because I can't access the data from the Database array. Please help.
If idNumb is unique then instead of:
DictionarySample[] database = new DictionarySample[1000];
you could use:
Dictionary<int, DictionarySample> = new Dictionary<int, DictionarySample>();
And then save the idNumb as the key of the dictionary.

How to compare new and previous value in combobox?

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;
}
}

Categories