ErrorProvider in an User control in C# - c#

I have an UserControl CambioContraseña with two textBox of other customized UserControl called txtAlfanumerico. This UserContol is very simple but I want to add an ErrorProvider to check the fields are not empty. This is a screen capture of UserControl:
And this is an code:
public bool FaltaCampos() {
bool falta = false;
foreach(txtAlfanumerico txt in Controls.OfType < txtAlfanumerico > ()) {
if (txt.Text == "") {
errorProviderFalta.SetError(txt, "Falta " + txt.Tag.ToString());
falta = true;
} else {
errorProviderFalta.SetError(txt, "");
}
}
return falta;
}
And the code in where I use this UserControl:
private void buttonConfirmar_Click(object sender, EventArgs e) {
try {
if (!cambioContraseña1.FaltaCampos()) {
string actual = cambioContraseña1.TextBoxContraseñaActual();
string nueva = cambioContraseña1.TextBoxNuevaContraseña();
persona.CambiarContraseña(actual, nueva);
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
But my problem is that ErrorProvider do not work in the Form that I use, icons do not appear directly.
I did a breakpoint into FaltaCampos and these are results:

I can to resolve my problem I think that I had not compiled the UserControl when I did the changes, so the ErrorProvider didn't appear.

Related

c# Populating a ListView from an XML File

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
}

dataGridView default error dialog handle

I am trying to hide default datagridview error dialog.
I put in the code this event handler:
this.dataGridView2.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(dataGridView2_DataError);
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//empty so it doesn't show anything
}
But still when i try this and leave datagridview cell empty ( delete everything from it), it show me dialog box with error.
Screenshot of error:
Try to Handle and Cancel the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Also, subscribe to the event in InitializeComponent()
private void InitializeComponent()
{
//...
this.dataGridView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView2_DataError);
}
try to use this code to handle the event:
private void dataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
Try the next code , it's work!
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
try
{
//To handle 'ConstraintException' default error dialog (for example, unique value)
if ((e.Exception) is System.Data.ConstraintException)
{
// ErrorText glyphs show
dataGridView1.Rows[e.RowIndex].ErrorText = "must be unique value";
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "must be unique value";
//...or MessageBox show
MessageBox.Show(e.Exception.Message, "Error ConstraintException",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
//Suppress a ConstraintException
e.ThrowException = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR: dataGridView1_DataError",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

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

minimizing to notification area and double click is not opening it back up

I am trying to get my application to minimize to the notification area and that part is working. The problem is, when I double click it, it is not showing the window again.
This is what I'm doing, I hope it's something simple I'm doing wrong:
public partial class Main : Form
{
public Main()
{
InitializeComponent();
CreateNotifyIcon();
}
private void CreateNotifyIcon()
{
mynotifyicon.BalloonTipIcon = ToolTipIcon.Info;
mynotifyicon.BalloonTipText = "[Balloon Text when Minimized]";
mynotifyicon.BalloonTipTitle = "[Balloon Title when Minimized]";
mynotifyicon.Icon = Resources.lightning;
mynotifyicon.Text = "[Message shown when hovering over tray icon]";
}
private void MainLoad(object sender, EventArgs e)
{
Resize += MainResize;
MouseDoubleClick += MainMouseDoubleClick;
}
private void MainResize(object sender, EventArgs e)
{
try
{
if (FormWindowState.Minimized == WindowState)
{
mynotifyicon.Visible = true;
mynotifyicon.ShowBalloonTip(3000);
ShowInTaskbar = false;
Hide();
}
else if (FormWindowState.Normal == WindowState)
{
mynotifyicon.Visible = false;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private void MainMouseDoubleClick(object sender, MouseEventArgs e)
{
try
{
Show();
WindowState = FormWindowState.Normal;
ShowInTaskbar = true;
mynotifyicon.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
Something I forgot to mention was I put a debug stop on MainMouseDoubleClick and it's never hitting that point.
Thanks for the help!
** EDIT **
I changed the double click to have a try/catch and it's not being reached at all. Not even to the try.
You need to add the click event to the notifyicon. At the moment you are registering the handler on the form.
mynotifyicon.MouseDoubleClick += MainMouseDoubleClick;
Attach the MouseDoubleClick event at the end of CreateNotifyIcon:
mynotifyicon.MouseDoubleClick += MainMouseDoubleClick;
I would recommend renaming the event handler MainMouseDoubleClick to something more appropriate and unregistering it from the form's double click event.
I have used this and its working :
this.WindowState = FormWindowState.Normal;
this.Activate();

C# child form not refreshing

I have this code that works fine when I call it from within the form, however, when I call the same from the Parent it runs through the code without results:
public void hideHelp()
{
//Check in db if panel1 is visible
SqlCeCommand checkHelp = new SqlCeCommand("Select Show_Help from Options where Opt_Id = 1", this.optionsTableAdapter.Connection);
if (this.optionsTableAdapter.Connection.State == ConnectionState.Closed)
{ this.optionsTableAdapter.Connection.Open(); }
try
{
bool showHelp = (bool)(checkHelp.ExecuteScalar());
this.panel1.Visible = showHelp;
this.Refresh();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
On Main form I have a toggle button with the following code:
private void tglHelp_Click(object sender, EventArgs e)
{
if (tglHelp.ToggleState.ToString() == "On")
{
HRDataSet.OptionsRow updateHelp = hRDataSet.Options.FindByOpt_Id(1);
try
{
updateHelp.Show_Help = true;
this.optionsTableAdapter.Update(this.hRDataSet);
Form activeChild = this.ActiveMdiChild;
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
tglHelp.Text = "Help Panel \nOFF";
}
Any ideas?
In this piece of code
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
you open another frmAddEmployees and add to the MDI, but you don't show it.
If your intent was to call the code in the current frmAddEmployees identified by the activeChild you should use something like this
if (activeChild.Name == "frmAddEmployees")
{
((frmAddEmployees)activeChild).hideHelp();
}

Categories