Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I've been strugling with this error for a while now.
I'm trying to implement a log in to an ATM system and I'm trying to connect it to a database as well. But when I try to run it, shows up 144 errors that are all the same:
'MyForm2': is not a member of 'jiji'
'MyForm2': undeclared identifier
Syntax error: missing ';' before identifier 'f2'
'f2':undeclared identifier
I honestly don't know why is this happening. I've tried to include MyForm2.h in the main code but nothing changes.
Here I leve the piece of code that is nearly the same for all my 7 forms ( except the 2nd that is the one that is giving the error I think)
MyForm.h:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
try {
String^ User = textBox1->Text;
String^ Pwd = textBox2->Text;
int AN = Int32::Parse(textBox3->Text);
String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=visualcppdb";
MySqlConnection^ con = gcnew MySqlConnection(constr);
MySqlDataAdapter^ da = gcnew MySqlDataAdapter("Select AccountNum from Userinfo WHERE AccountNum = '" + AN + "'", con);
DataTable^ dt = gcnew DataTable();
da->Fill(dt);
if (dt->Rows->Count >= 1) {
MySqlCommand^ cmd = gcnew MySqlCommand("insert into Db values (" + AN + ") ", con);
con->Open();
MySqlDataReader^ dr = cmd->ExecuteReader();
con->Close();
try {
this->Hide();
jiji::MyForm2 f2;
f2.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
else {
MessageBox::Show("User does not exist, try again");
}
}
catch (Exception^ e) {
MessageBox::Show(e->Message);
}
}
By the way AN is the Account number.
The MyForm2.h code is the same over and over again except for the ending.
MyForm2.h:
//Extract money
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
try {
this->Hide();
jiji::MyForm3 f3;
f3.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
//Insert Money
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
try {
this->Hide();
jiji::MyForm4 f4;
f4.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
//Transfer
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
try {
this->Hide();
jiji::MyForm5 f5;
f5.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
//Check Amount
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
try {
this->Hide();
jiji::MyForm6 f6;
f6.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
//Reload phone
private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) {
try {
this->Hide();
jiji::MyForm7 f7;
f7.ShowDialog();
this->Show();
}
finally {
this->Close();
}
}
//Exit
private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) {
try {
String^ constr = "Server=127.0.0.1;Uid=root;Pwd=;Database=visualcppdb";
MySqlConnection^ con = gcnew MySqlConnection(constr);
MySqlCommand^ cmd = gcnew MySqlCommand("TRUNCATE Db ", con);
con->Open();
MySqlDataReader^ dr = cmd->ExecuteReader();
con->Close();
}
catch (Exception^ e) {
MessageBox::Show(e->Message);
}
finally {
this->Close();
}
}
Perhaps you aren't including MyForm2.h in a context MyForm.h can access?
Maybe look into how to declare a namespace and how to include headers, e.g. Creating a C++ namespace in header and source (cpp)
What happens if you inline the MyForm2 class definition into MyForm so you guarantee it is accessible?
Related
Im trying to limit the user input to float or integer by using this function I found from another post.
private: System::Void keypressValidation(System::Windows::Forms::TextBox^ textBox, System::Windows::Forms::KeyPressEventArgs^ e) {
// Only allow 1 decimal point
if (e->KeyChar == '.')
{
if (textBox->Text->Contains(".") && !textBox->SelectedText->Contains("."))
{
e->Handled = true;
}
}
// Accepts only digits and Backspace keypress
else if (!Char::IsDigit(e->KeyChar) && e->KeyChar != 0x08)
{
e->Handled = true;
}
}
Right now I have 8 textboxes on my UI and I created 8 different keypress event handler for every individual textbox.
private: System::Void txtN3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN3, e);
}
private: System::Void txtN2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN2, e);
}
private: System::Void txtN1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN1, e);
}
private: System::Void txtN0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN0, e);
}
private: System::Void txtD3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD3, e);
}
private: System::Void txtD2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD2, e);
}
private: System::Void txtD1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD1, e);
}
private: System::Void txtD0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD0, e);
}
But later on in my project I will have around 64 textboxes and I find it too tedious to have an event handler for every textboxes.
Is there a method which will make this more compact such as only having one event handler for multiple textboxes?
You absolutely can do this with only a single handler function. First you must deal with the small difference between the functions:
void txtGeneric_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{
keypressValidation(safe_cast<TextBox^>(sender), e);
}
Then it is a simple matter in the designer of wiring up the event on every textbox to this unified handler. Instead of double-clicking on the handler entry in the event list, use the drop-down to select the existing function.
Another option is to remove all the handlers in the designer and wire them up at runtime, as suggested by #EylM. Note that his loop will only work if every single textbox on the form is treated the same way, if you have even one or two that aren't part of the pattern, you'll need more complicated filtering.
My preferred way would be to iterate over all textboxes in the Form and bind a single event handler.
Here is the sample code in C++/CLI:
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
for each (Control ^ ctrl in this->Controls)
{
if (ctrl->GetType() == TextBox::typeid)
{
ctrl->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox1_KeyPress);
}
}
}
private: System::Void textBox1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{
}
I'm new in programming Windows Form Application. I want to capture my Windows form (with the function CaptureScreen()) and save it to a file by clicking on a button using the SaveFileDialog. Here my code:
private: System::Void CaptureScreen()
{
Drawing::Graphics^ myGraphics = this->CreateGraphics();
memoryImage = gcnew Drawing::Bitmap(Size.Width, Size.Height, myGraphics);
Drawing::Graphics^ memoryGraphics = Drawing::Graphics::FromImage(memoryImage);
memoryGraphics->CopyFromScreen(this->Location.X, this->Location.Y, 0, 0, this->Size);
}
private: System::Void btnSave_Click(System::Object^ sender, System::EventArgs^ e)
{
SaveFileDialog^ saveDiag2 = gcnew SaveFileDialog();
saveDiag2->Filter = "Dateityp PNG (*.PNG)|*.PNG|All files (*.*)|*.*";
saveDiag2->FilterIndex = 1;
saveDiag2->RestoreDirectory = true;
if (saveDiag2->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
String^ savePath = saveDiag2->FileName;
if (saveDiag2->OpenFile() != nullptr)
{
try
{
CaptureScreen();
if (memoryImage != nullptr)
{
memoryImage->Save(savePath, Imaging::ImageFormat::Png);
}
}
catch (Exception^)
{
MessageBox::Show("There was a problem saving the file."
"Check the file permissions.");
}
}
}
}
I always get the Exception displayed. What am I doing wrong?
Hans Passant is right. You should dispose IDisposible objects. In C++ CLI you can do it with help of msclr::auto_handle smart pointer.
#include <msclr/auto_handle.h>
private: System::Void CaptureScreen()
{
msclr::auto_handle<Drawing::Graphics> myGraphics(this->CreateGraphics());
memoryImage = gcnew Drawing::Bitmap(Size.Width, Size.Height, myGraphics.get());
msclr::auto_handle<Drawing::Graphics> memoryGraphics(Drawing::Graphics::FromImage(memoryImage));
memoryGraphics->CopyFromScreen(this->Location.X, this->Location.Y, 0, 0, this->Size);
}
Also you can retrieve usefull information from Exception object:
catch (Exception^ exception)
{
MessageBox::Show("There was a problem saving the file: " + exception->ToString(),
"Check the file permissions.");
}
I can't update my WinForm label properties.
Details: I am trying to check my database and get some values posted, but I can't even update a mere label it seems. I'm using SharpDevelop.
The code:
//this is my form
public partial class MainForm : Form
{
//Declaring timer
public static System.Timers.Timer aTimer = new System.Timers.Timer();
public MainForm()
{
InitializeComponent();
//Timer
aTimer.Elapsed +=new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text="some_text";
}
private static void OnTimedEvent(object source, ElapsedEventArgs e) {Check();}
public static void Check()
{
//Database checks here..
try{label1.Text="new_text";}catch(Exception e) {MessageBox.Show(e.ToString());}
MessageBox.Show("BAAAA");
}
void Button1Click(object sender, EventArgs e)
{
label1.Text = "mergeeeeee?!";
}
}
EDIT: I've removed all static modifiers. Also updated the post with the new code (try catch is added and the messagebox after it + a button that changes the label).
The try catches the following error:
. Really could use some help, been researching answers for more than 6 hours.
Try this (use a System.Windows.Forms.Timer instead of System.Timers.Timer):
//Declaring timer
public System.Windows.Forms.Timer aTimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
//Timer
aTimer.Tick += aTimer_Tick;
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text = "some_text";
}
void aTimer_Tick(object sender, EventArgs e)
{
Check();
}
public void Check()
{
try
{
//Database checks here..
label1.Text = string.Format("new_text {0}", DateTime.Now.ToLongTimeString());
}
catch (Exception ex)
{
throw ex;
}
MessageBox.Show("BAAAA");
}
The Elapsed event of the System.Timers.Timer is fired on a non-UI thread (change your original code to not swallow exceptions and you should see the cross-thread exception).
I used the following code for my project and it worked.
It has a button to activate the timer and the timer raises an event when 500 milliseconds passed.
private void ActiveTimer_Click(object sender, EventArgs e)
{
EnableTimer();
}
private void EnableTimer()
{
System.Timers.Timer raiseTimer = new System.Timers.Timer();
raiseTimer.Interval = 500;
raiseTimer.Elapsed += RaiseTimerEvent;
raiseTimer.AutoReset = true;
raiseTimer.Enabled = true;
}
private void RaiseTimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
this.Invoke(new Action(() =>
{
label1.Text += "500 ms passed\n";
}));
}
I need to build an array to contain objects. However, it does not work and I could not find out the error myself. Please help
# include "CRegistration.h" //My object class
SKIP MANY LINES
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
array<CRegistration^> ^CregArray = gcnew array<CRegistration^>(100);
record_number = 0;
}
private: System::Void MyAdd_Click(System::Object^ sender, System::EventArgs^ e) {
Form2^ myForm2 = gcnew Form2();
if (myForm2->ShowDialog()==System::Windows::Forms::DialogResult::OK) {
record_number = record_number + 1;
CRegistration^ Creg = gcnew CRegistration(System::Convert::ToString(record_number),myForm2->TempReg[0],myForm2->TempReg[1],myForm2->TempReg[2],myForm2->TempReg[3]);
CregArray[record_number-1] = Creg;
}
}
};
change line
array<CRegistration^> ^CregArray = gcnew array<CRegistration^>(100);
to
CregArray = gcnew array<CRegistration^>(100);
add field declaration:
Form1(void)
{
..
}
array<CRegistration^> ^CregArray;
private: System::Void MyAdd_Click(System::Object^ sender, System::EventArgs^ e) {
..
}
I am building a proof of concept application before it gets rollout to the real one.
Scenario
I should be able to stop processing in the middle of it.
Toolbar 2 buttons "Start" & "Stop"
User press start and it process a long running task.
User decides out of the blue to stop the task.
I cannot seem to get threading right!! I cannot press stop as it's waiting for the long running task as if the long running task is actually running on UI thread and not as intented on background thread.
What Am I doing wrong can you spot it? Thanks for your help
public partial class TestView : UserControl
{
private readonly BackgroundWorker _worker;
public TestView
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.RunWorkerCompleted += RunWorkerCompleted;
_worker.DoWork+=DoWork;
_worker.WorkerReportsProgress = true;
_worker.ProgressChanged+=_worker_ProgressChanged;
_worker.WorkerSupportsCancellation = true;
}
static void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + e.Error);
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result);
}
}
private delegate void SimpleDelegate();
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
_worker.ReportProgress(i, DateTime.Now);
// SimpleDelegate simpleDelegate = () => txtResult.AppendText("Test" + System.Environment.NewLine);
//Dispatcher.BeginInvoke(DispatcherPriority.Normal, simpleDelegate);
}
MessageBox.Show("I have done it all");
}
private void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
DateTime time = Convert.ToDateTime(e.UserState);
txtResult.AppendText(time.ToLongTimeString());
txtResult.AppendText(Environment.NewLine);
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
_worker.RunWorkerAsync();
}
private void BtnStop_Click(object sender, RoutedEventArgs e)
{
_worker.CancelAsync();
MessageBox.Show("Process has been stopped!");
}
}
You run a very tight loop inside of DoWork and continuously push Invoked ProgressUpdates to the Main Thread. That will make it sluggish.
But the real problem is that DoWork has to cooperate in Cancellation:
void DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 1000000; i++)
{
if (_worker.CancelationPending)
{
e.Cancel = true;
break; // or: return to skip the messagebox
}
_worker.ReportProgress(i, DateTime.Now);
}
MessageBox.Show("I have done it all"); // remove or make depend on Cancelled
}