Windows Form Designer not showing up - c#

I'm working on our little project and when I saved my work and exit on Visual Studio. I found that the designer wasn't showing up, and it's just a bunch of code, then there was this LoginForm.Designer.cs file. My problem is how can I make the designer show up again because I have to customize more on the UI of the project
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InventoryManagementSystem
{
public partial class LoginForm : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acer\Documents\dbIMS.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
public LoginForm()
{
InitializeComponent();
}
private void checkBoxPass_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxPass.Checked == false)
txtPass.UseSystemPasswordChar = true;
else
txtPass.UseSystemPasswordChar = false;
}
private void lblClear_Click(object sender, EventArgs e)
{
txtName.Clear();
txtPass.Clear();
}
private void pictureBoxClose_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Exit Applicaton", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Application.Exit();
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
cm = new SqlCommand("SELECT * FROM tbUser WHERE username=#username AND password=#password", con);
cm.Parameters.AddWithValue("#username", txtName.Text);
cm.Parameters.AddWithValue("#password", txtPass.Text);
con.Open();
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
MessageBox.Show("Welcome " + dr["fullname"].ToString() + " | ", "ACCESS GRANTED", MessageBoxButtons.OK, MessageBoxIcon.Information);
MainForm main = new MainForm();
this.Hide();
main.ShowDialog();
}
else
{
MessageBox.Show("Invalid username or password!", "ACCESS DENITED", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
This is the code on my LoginForm.cs
I tried different solutions on YouTube and google like shift +f7 but it's still not showing up

My problem is how can I make the designer show up again
VS2022 is a bit buggy with the WinForm designer. Not the ideal solution but you can fix it by commenting out all the code in the Form1.cs except for :
public LoginForm()
{
InitializeComponent();
}
Goto Definition of InitializeComponent() and look for all the red dots on the right margin, mainly Event += Handlers and comment these out.
Now view the form designer. Bit by bit bring back the events in the form1.designer.cs and uncomment the corresponding events in the form1.cs
The trick is to narrow down the problem.

Related

Inserting Data Into SQL Server Database Through DataGridView Not Working In Visual Studio

I'm trying to get the data in my "Jokes" table to update in SQL Server when I change the cell(s) in this DataGridView and click the "Update" button I made. I tried following along with a tutorial, but it seems to just not work. What do I need to change here to make it work? I'm not getting any errors oddly, so it must just be the way I did it or something. Thanks for any help.
This is the entire code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace TestProject1
{
public partial class UserControl3 : UserControl
{
SqlConnection con = new SqlConnection(#"Data Source=MSI;Initial Catalog=Jokes;Integrated Security=True;");
SqlDataAdapter adpt;
DataTable dt;
DataSet ds;
SqlCommandBuilder cmdbl;
public UserControl3()
{
InitializeComponent();
ShowData();
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.jokesTableAdapter.FillBy(this.jokesDataSet.Jokes);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void UserControl3_Load(object sender, EventArgs e)
{
con.Open();
ds = new DataSet();
adpt.Fill(ds, "Jokes");
}
public void ShowData()
{
adpt = new SqlDataAdapter("SELECT * FROM Jokes", con);
dt = new DataTable();
adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
private void BackGridButton_Click(object sender, EventArgs e)
{
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
cmdbl = new SqlCommandBuilder(adpt);
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Double check (by debugging) whether the property builder.GetUpdateCommand().CommandText is returning a valid update command.
If not, add the update your try-block in button1_Click to look like this
cmdbl = new SqlCommandBuilder(adpt);
adpt.UpdateCommand = cmdbl.GetUpdateCommand();
adpt.Update(ds, "Jokes");
MessageBox.Show("Jokes Updated");
I do admit that the second in line above code snippet should not be required theoretically looking at the way you instantiated the SqlCommandbuilder. But it would just be to re-affirm and also part of the reason why I suggested to check that property in Debug mode.

Set a Label text in 1st winform page to display on 2nd form page

Im fairly new to C# so please forgive me if my terminology isn't to par. In my winform application I want to grab a name from a MySQL database # login and display the name on a second page(home.cs). Im currently getting an error which is "An Object Reference is required for the non static field. In login.cs im trying to add something like -> Home.bunifuCustomLabel2.Text = "test"; to set the label in home.cs basically... Login.cs is my 1st loading page and Home.cs is my 2nd page which loads after successful login. I would like to query the database while the connection is open and eventually set the label text for home.cs to display something like Welcome, Name
LOGIN.CS:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
Home.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
Home fm = new Home();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
HOME.CS:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Welcome to C# world! Changing code of logic.cs to following will eliminate the problem you are facing.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Firemax
{
public partial class Login : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=xyz.com;port=3333;Initial Catalog = test_db;User Id = fml;password=imscrewed");
int i;
public Login()
{
InitializeComponent();
this.CenterToScreen();
}
private void BunifuMaterialTextbox1_OnValueChanged(object sender, EventArgs e)
{
}
private void BunifuMaterialTextbox2_OnValueChanged(object sender, EventArgs e)
{
bunifuMaterialTextbox2.isPassword = true;
}
private void BunifuFlatButton1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from users where username='" + bunifuMaterialTextbox1.Text + "' and password='" + bunifuMaterialTextbox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
Home fm = new Home();
if (i==0)
{
bunifuCustomLabel3.Text = "You have entered either a wrong Username and/or Password";
fm.bunifuCustomLabel2.Text = "test";
}
else
{
this.Hide();
fm.Show();
fm.Location = this.Location;
}
con.Close();
}
private void BunifuMaterialTextbox1_OnValueChanged_1(object sender, EventArgs e)
{
}
private void BunifuImageButton1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Your code needs improvements. I would highly recommend investing 70 minutes in C# video series by Mosh.
Maybe this can help you
In your first activity
public static string myText= "";
myText=myLabel.Text;
In your second activity Form_Load
seconLabel.Text = Form3.myText;

C# Login Form, Login Button Doesn't Respond

So, I'm new to VS and C#, I'm self-teaching to get a better understanding of the backend of the product I work with. I created a small database with some information and a Login form. Everything appears to compile correctly, but the login button doesn't respond when clicked, neither does the cancel button for that matter. Not sure what I am missing, code is below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CorpLogin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//DB Connection String
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CORPORATION.mdf;" +
"Integrated Security=True";
//Login Button clicked
private void LoginButton1_Click(object sender, EventArgs e)
{
//Validates text entered
if (userNameText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}
if (passwordText1.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD are required fields.");
return;
}
try
{
//Connect to SQL
SqlConnection con = new SqlConnection(cs);
con.Open();
SqlCommand cmd = new SqlCommand("select * from USERS where USERNAME=#username" +
"and PASSWORD=#password", con);
cmd.Parameters.AddWithValue("#username", userNameText1.Text);
cmd.Parameters.AddWithValue("#password", passwordText1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
int count = ds.Tables[0].Rows.Count;
//Show new form or fail message
if (count == 1)
{
this.Hide();
CorpView cv = new CorpView();
cv.Show();
}
else
{
MessageBox.Show("ACCESS DENIED");
}
}
//Catch program exceptions
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Cancel Button Clicked
private void CancelButton1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Any help is appreciated. Thanks.
You also have to add the event handler Registration.
This can be done in the designer by double-click the button, or manually in your form:
LoginButton1.Click += new System.EventHandler(LoginButton1_Click);
So the cause of my issue was as mentioned above. I did not have the event handlers mapped to the buttons. From the designer, I looked up the properties and selected the event methods (lightning bolt icon), in click I set the login button to LoginButton1_Click and on the cancel button I set it to CancelButton1_Click.
I am running into an error with the database connection, but I know how to troubleshoot that. The cancel button closes the program as expected.

Pop up access denied message when certain button is clicked depending on which user has logged in

In login form, When I login as Jack which exist in the DOCTOR table, it will go to page_two. I want to pop up a access denied message if nurse button 1 or nurse button 2 is clicked since Jack is not a nurse but a doctor. Then for the opposite, if I login as Mary, which exist in the NURSE table, it will go to page_two. I want to pop up a access denied message when doctor button 1 or doctor button 2 is clicked since Mary is not a doctor but a nurse.
The button names for Page_two is btnDoctor1, btnDoctor2, btnNurse1 and btnNurse2
**//login Form codes**
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace GRP_02_03_SACP
{
public partial class page_one : Form
{
public page_one()
{
InitializeComponent();
}
private void page_one_Load(object sender, EventArgs e)
{
}
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
page_two form = new page_two();
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
}
}
//Page_two codes
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
public page_two()
{
InitializeComponent();
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}
Add This To your Code :
public Int JobPosition;
Here you will Define the position for each.
Change the Code on your btnLogin_Click to this :
private void btnLogin_Click(object sender, EventArgs e)
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandtext = "SELECT dUsername, dPassword from DOCTOR";
// Add a WHERE Clause to SQL statement
strCommandtext += " WHERE dUsername=#dname AND dPassword=#dpwd;";
strCommandtext += "SELECT nUsername, nPassword from NURSE WHERE nUsername=#nname AND nPassword=#npwd;";
SqlCommand cmd = new SqlCommand(strCommandtext, myConnect);
cmd.Parameters.AddWithValue("#dname", textUsername.Text);
cmd.Parameters.AddWithValue("#dpwd", txtPassword.Text);
cmd.Parameters.AddWithValue("#nname", textUsername.Text);
cmd.Parameters.AddWithValue("#npwd", txtPassword.Text);
try
{
// STEP 3: open connection and retrieve data by calling ExecuteReader
myConnect.Open();
// STEP 4: Access Data
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) //For Doctor
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 1; //Doctor
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
reader.NextResult();
while (reader.Read()) //For Nurse
{
if (MessageBox.Show("Login Successful") == DialogResult.OK)
{
JobPosition = 2; //Nurse
page_two form = new page_two(JobPosition);
form.Show();
return;
}
}
//STEP 5: close connection
reader.Close();
MessageBox.Show("Invalid username or password");
}
catch (SqlException ex)
{
}
finally
{
//STEP 5: close connection
myConnect.Close();
}
}
On Page_two Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GRP_02_03_SACP
{
public partial class page_two : Form
{
private Int JopPosition;
public page_two()
{
InitializeComponent();
}
public page_two(Int _Position)
{
InitializeComponent();
JopPosition = _Position;
}
private void btnDoctor1_Click(object sender, EventArgs e)
{
}
private void btnDoctor2_Click(object sender, EventArgs e)
{
}
private void btnNurse1_Click(object sender, EventArgs e)
{
if (JopPosition == 1)
{
MessageBox.Show("access denied");
}
}
private void btnNurse2_Click(object sender, EventArgs e)
{
}
}
}

Null reference on SQL connection object

I am new to C#. I have created the login screen.I this one am not able to check the username and password.This is my code.Can anyone help me please.Thanks in advance.Please don't hesitate to copy the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Voting_Editor_Tool
{
public partial class Form1 : Form
{
SqlConnection cn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string username = txtusername.Text;
string password = txtpassword.Text;
if (ValidateUserNamePassword(username, password))
{
// move to next form or do whatever you need to do after a successfull login
}
else
{
MessageBox.Show("Invalid user name or password", "Invalid Login");
return;
}
}
public bool ValidateUserNamePassword(string _username, string _password)
{
// string connectionString = "Data Source=[servername];Initial Catalog=[databaseName];User ID=[Admin Login];Password=[Admin Password];";
using (SqlConnection cn= new SqlConnection(#"User ID=sa;Password=password123;Initial Catalog=dish_tv;Data Source=ENMEDIA-CCDDFE5\ENMEDIA"));
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "tsp_GetUserNameAndPassword";
SqlParameterCollection sqlParams = cmd.Parameters;
sqlParams.AddWithValue("#username", _username);
sqlParams.AddWithValue("#password", _password);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (dr.Read())
{
// this will return true if a row matching the username and password is found.
// this means that the user's input is valid
return true;
}
else
{
return false;
}
dr.Close();
cn.Close();
}
}
}
}
Remove your using clause and put that piece of code into Try.. catch block. Catch the exception object and read its stacktrace. Check the connection string carefully for any typo mistakes. This should give you much more details to debug than generic error like "Object reference not set to an instance of an object"
You have a semi-colon at the end of your using statement, therefore terminating the using. Remove the semi-colon and it will work.

Categories

Resources