Wrong form is being closed [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
why is the form named (Smart_pharmacy) being closed when I execute this code :
private void LoginBTN_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "select userpass from usertab where username = #username";
com.Parameters.Add("#username", usernametxt.Text);
con.Open();
object returnedvalue = com.ExecuteScalar();
if (returnedvalue != null)
{
string returneduserpass = com.ExecuteScalar().ToString();
con.Close();
if (returneduserpass == userpasstxt.Text)
{
Smart_Pharmacy f = new Smart_Pharmacy();
f.Show();
this.Close();
}
else
{
MessageBox.Show("Incorrect username or password !");
}
}
else
{
MessageBox.Show("Incorrect username or password !");
}
}
I want the current form to be closed and keep the form (Smart_Pharmacy) opened please help.

I assume you have this code in your main form (one which is passed to Application.Run method in your Main method). When main application form is closed, all other forms are closed as well and application terminates.
What you should do is change application main form to Smart_Pharmacy. And close application if login failed. Like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using(LoginForm loginForm = new LoginForm())
{
if (loginForm.ShowDialog() != DialogResult.OK)
return; // exit applicatioin if login failed
}
// if login successfully this start main form
Application.Run(new Smart_Pharmacy());
}

I would say its because you created the Smart_Pharmacy form within the form that is then closed (ie. destroyed).
So the code does what you are telling it to...kill current form. Since the form is destroyed all objects referenced only within this form get destroyed too.
If you want the other form to stay open then you will have to keep a reference to it somewhere else.
PS: On an unrelated note, this code is horrible. You really shouldn't connect to db from button clicks and such. If you are in a position to revise this I would strongly suggest to separate your business logic from UI code.
Technically this works but you should always try to keep layered and easily maintainable.

I've had the same problem. I'm guessing that your login form is set as your start up form. In which case you would need to Hide it rather than close it.

Change to
Smart_Pharmacy f = new Smart_Pharmacy();
f.ShowDialog(this);
this.Close();
So this.Close() will execute after the Smart_Pharmacy form closed
if you need main form to be hidden, use this.WindowState = FormWindowState.Minimized; before opening Smart_Pharmacy

Related

How do I write data that is not deleted with database when the form is closed and opened?

private void btnPublish_Click(object sender, EventArgs e)
{
Sqlbaglan.NesneVer().thisConn = new SqlConnection(#"Data Source=(localdb)\mssqllocaldb;initial catalog = ManagerPanel;integrated security = true");
Sqlbaglan.NesneVer().thisConn.Open();
Sqlbaglan.NesneVer().thisQuery = new SqlCommand("SELECT Kurallar FROM [Rules] WHERE TC=#TC", Sqlbaglan.NesneVer().thisConn);
Sqlbaglan.NesneVer().thisQuery.Parameters.AddWithValue("#TC", tbxTC.Text);
label1.Text = Sqlbaglan.NesneVer().thisQuery.ExecuteScalar().ToString();
Sqlbaglan.NesneVer().thisConn.Close();
}
Friends, I have 2 problems, I do not have much knowledge of SQL, but I wanted to do my job with the database. I created a SQL connection and query object with singleton dp. I called the rule that has that TC with the TC entered in tbxTC and printed it on label1.Text in the SAME FORM. So far, everything happens as I want. My 1st problem is that when I open and close the form, label1.Text gets reset. Consider my second problem independent of my first problem. My second problem is that I have written in capital letters already - I am nervous- I have to show it in another form. This form's name is frm2. So consider label1.text is in another form.

Passing Variables and Setting Form Attributes Based on Passed Variables in C#

I've been through at least a dozen articles on StackOverflow and I have found similar issues and tried to piece things together, but I just can't figure it out.
I'm making a Windows Form App in C#.
It has a small "Login" form where they enter an ID, and it verifies the ID is good, and then the main page comes up.
If I start with the Login page, I can create a new main page, and pass the id and name from the login to the main page when it's created. The login is then hidden and the main page is shown. However, when you close the main page the app doesn't close because the login is still open and hidden. But if you close the login, it closes everything.
I think I need to start with the main page, and then create the login from the main page. That way I can close the login once it's confirmed, and it won't close everything. However, I can't figure out how to pass the ID and Name from the Login into the Main Page.
Here is what I have right now...
Program.cs
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form_Login frmLogin = new Form_Login();
if (frmLogin.ShowDialog() == DialogResult.OK) {
Application.Run(new Form_MainPage());
} else {
Application.Exit();
}
}
Form_Login.cs
public partial class Form_Login : Form {
public Form_Login() {
InitializeComponent();
txtBuyerID.Focus();
}
private void txtBuyerID_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
string connString = "Data Source=<server>;Initial Catalog=<database>;Integrated Security=true;";
string BuyerName = "";
string sql = "SELECT c.first_name + ' ' + c.last_name AS name FROM contacts c WHERE c.buyer='Y' AND c.id=#BuyerID";
using (SqlConnection conn = new SqlConnection(connString)) {
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#BuyerID", txtBuyerID.Text);
try {
conn.Open();
BuyerName = (string)cmd.ExecuteScalar();
Form_MainPage frmMainPage = new Form_MainPage(txtBuyerID.Text,BuyerName);
this.txtBuyerID.Text = BuyerName;
Hide();
} catch (Exception ex) {
Console.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
}
}
}
}
Form_MainPage.cs
public partial class Form_MainPage : Form {
public Form_MainPage(string BuyerID, string BuyerName) {
InitializeComponent();
this.Text = "BUYER: " + BuyerID + " - " + BuyerName;
this.Show();
}
}
At this point I'm all mixed up and confused. This was much easier when I did it way back in VB! What do I need to change to get the correct sequence of loading and passing of variables from the Login to the MainPage?
This shouldn't be difficult to do. I think you want to pass BuyerId and BuyerName from the LoginPage to the MainPage upon successful authentication.
Form_Login.cs should look like this.
Form_MainPage frmMainPage = new Form_MainPage();
On your MainPage, create labels for BuyerId and BuyerName. Ensure they have public modifiers.
frmMainPage.BuyerId.Text="ID";
frmMainPage.BuyerName.Text="BuyerName";
frmMainPage.Show();
this.Close(); //or Hide();
See if that helps.

MySQL connection doesnt close

I'm hitting a wall right now in my project.
I have a form, with some listboxes, and add button. When I click on the add button, I got a small dialog form with a textbox, an OK and a Cancel button. The app is connected to a MySQL database. So whenever the text change, the program checks if the name exists in the database, disable the OK button and the textbox turn red if the name exists, otherwise it turns them back to normal. Works without a problem when I'm writing and the name doesn't exist, and when it does, it turns red, like it should. And here is the problem. After turning red, it doesn't go back to normal, even when I enter a valid name.
Here is the code :
private void DialogTxb_TextChanged(object sender, EventArgs e)
{
//ConnexionData class where i do all the SQL manipulation
MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text);
while (selection.Read())
{
if (selection.HasRows)
{
DialogOk.Enabled = false;
toolTip1.Show("La section existe", TooltibLb);
DialogTxb.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffaaaa");
}
else
{
toolTip1.Hide(TooltibLb);
DialogTxb.BackColor = Color.White;
DialogOk.Enabled = true;
}
}
ConexionData.ConexionClose();//Method to close connection
}
I think I have an idea where the problem is but have don't know why it happens and how to solve it. If I simply exit the form and try to do anything else, like select another element from a listbox which will trigger some database interaction, the program close and visual studio provide me with info on the error:"The connexion is already open". I tried to close in other moments of the code, looked for some solutions on the internet, tried MysqlConection.ClearAllPools(), and still the same issue.
Connexion opens and closes properly in other parts of the application.
Thanks for your attention.
Edit
Here are the methods in ConexionData
class ConnexionData
{
private static MySqlConnection Connexion;
public static MySqlCommand Command;
//Many other methods
//.......
public static void ConnexionClose()
{
Connexion.Close();
}
public static MySqlDataReader CheckSectionName(string name)
{
Connexion.Open();
string checkSectionName = ("Select sectionName from section where sectionName = '" + name + "'");
Command.CommandText = checkSectionName;
Reader = Command.ExecuteReader();
return Reader;
}
}
I use the Connexion.Close() in many parts of the program. I have 2 Data Grid views, and some list box where i load data from the database. I open and close those DGV and change values in listbox and all work fine. Then i try my small form to insert a new values on those tables, test it and close it (actually i insert nothing, i simply close it and there is a ConexionData.Close() in the close event) and here where the problem of connection start.
Edit-Solved
I finally solved the problem. I turned Private MysqlConection to public, and directly closed the property after closing the dialog.
if selection.Read() returns true it means you have at least 1 record. It seems you are looking for
private void DialogTxb_TextChanged(object sender, EventArgs e) {
try {
//TODO: check ConexionData.CheckSectionName (re-)creates connection if required
using (MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text)) {
if (selection.Read()) {
// Name exists (we've read it)
DialogOk.Enabled = false;
toolTip1.Show("La section existe", TooltibLb);
DialogTxb.BackColor = System.Drawing.ColorTranslator.FromHtml("#ffaaaa");
}
else {
// Name doesn't exist: the cursor is empty (so we've failed to read it)
toolTip1.Hide(TooltibLb);
DialogTxb.BackColor = Color.White;
DialogOk.Enabled = true;
}
}
}
finally {
// finally: rain or shine the connection should be closed
ConexionData.ConexionClose(); // Method to close connection
}
}
In case connection is not closing then you can try to call close() connection or sqldatareader before executing method "CheckSectionName()".
FYR Below is some example Let me know, if it helps.
Approch 1:
System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection();
if(sqlConn.State!= System.Data.ConnectionState.Closed)
{
sqlConn.Close();
}
System.Data.SqlClient.SqlDataReader SqlReader= new System.Data.SqlClient.SqlDataReader();
if(!SqlReader.IsClosed)
{
SqlReader.Close();
}
MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text);
Approch 2: We can use "using" clause
using (MySqlDataReader selection = ConexionData.CheckSectionName(DialogTxb.Text))
Approch 3:
Add close() and dispose() into finally block.

Sending variables between forms [duplicate]

This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 7 years ago.
I am making a game, and I have 3 main forms that I am using, one is the start menu, one is the main game form, and the other is a create map form. My question is directed to how can I send variables between them. I know of the classic form setup, where you show one form from the other, and pass information like this...
Form1 form = new Form1();
form.Show();
form.varible = ...
But i don't like how the previous form is still showing, and form.ShowDialog isn't what I am going for either. I have a system where you cycle through forms, where it opens your new form and closes the old one, and it works great, except I don't know how to send information to the new form. I changed the Program.cs code to look like this
public static bool OpenForm1OnClose { get; set; }
public static bool OpenForm2OnClose { get; set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OpenForm1OnClose = true;
OpenForm2OnClose = false;
while (OpenForm1OnClose || OpenForm2OnClose)
{
if(OpenForm1OnClose)
Application.Run(new Form1());
if (OpenForm2OnClose)
Application.Run(new Form2());
}
}
This is just a testing program right now that switches between two forms - click one button and it goes to the other form and closes the one you were on. Here's what the button click code looks like
private void button1_Click(object sender, EventArgs e) // form1's button
{
Program.OpenForm2OnClose = true;
this.Close();
}
That is all the code right there, nothing more to it really. Any Idea's on how to pass variables would be awesome, or if its straight up impossible, advice on a good way to switch between forms would be helpful. Thanks for reading
If you're asking what I think, the answer is simple. You just need to have your constructor take the information as its args.
private var myInfo;
public Form1(var myInfo_)
{
InitializeComponent();
myInfo = myInfo_;
}
I hope this is in fact what you want.

C# DialogForm opening when calling for mainForm

I have a problem with my dialogForm. This is the code that opens my dialogForm (this is a login form) when my mainForm starts to run.
private void indexForm_Load(object sender, EventArgs e)
{
startForm loginForm = new startForm();
loginForm.ShowDialog();
indexUsername.Text = klasseGebruikersnaam.gebruikersnaam;
}
So when my indexForm (Main form) starts , it first loads a dialogForm, which is my login form.
Now my problem is that whenever I try to acces the mainForm from another form using this code (for example when I click a button):
this.Hide();
indexForm inf = new indexForm();
inf.Show();
The dialogForm pops up again. So I want to show my mainForm but , when I load my mainForm my dialogForm always pops up.
Any way around this?
Thanks in advance.
The problem is that you are loading your loginForm from your Main Form's Load event. Which is always going to fire after the constructor of the Main Form is called. Typically you will want to launch the loginForm from somewhere before the Main Form is loaded. You could do this in your Program.cs file and make it the main entry point of the program. Or just simply check if the user is already logged in.
Here is an example of both:
Program.cs
static void Main()
{
//Auto-generated code that VS writes for you
using (var loginForm = new LoginForm())
{
if (loginForm.ShowDialog() == DialogResult.Yes) //Presumably it would only return Yes if the login was successful.
{
Application.Run(new MainForm()); //Or however you call your main form
}
}
}
Of you can just put a property on the Main Form that determines if the user is logged in. Then you can call it in the Load event still.
Load Event
if(!this.UserLoggedIn)
{
loginForm.ShowDialog();
//Do something with the dialog result.
}
In my opinion it is better to user the Program.cs approach because if the user fails to login correctly, you can just exit or handle it as needed without loading your Main Form at all. The way you currently have it, the main form must load before the login form is shown, which could be problematic.
Well, you should remove that code from your main form and call it before showing the main form.
Or you could simply set a global variable that keeps the info for the current logged in user and, if that variable is not null, don't call again the login form
So, supppose that you login form prepare an instance variable of type LoggedinUser
public class LoggedinUser
{
public string NickName {get;set;}
public string UserRole {get; set;}
...
}
then in an utility class (or in your index form) you could have a static variable
public static LoggedinUser currentOperator = null;
in your in index_form you could write
if(GlobaClass.currentOperator == null)
{
using(startForm loginForm = new startForm())
{
if(loginForm.ShowDialog() == DialogResult.OK)
GlobalClass.currentOperator = loginForm.LoggedUser;
}
}
looks like you need to add a check to see if the user is logged in around the
loginForm.ShowDialog();
something like
if(!UserLoggedIn())
{
loginForm.ShowDialog();
}

Categories

Resources