Why do i keep getting a blank form C# - c#

I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form code:
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;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form code:
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;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.

You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation

Related

How to fix Error in argument exception system

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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pwnew.PasswordChar = '*';
pwtxt.PasswordChar = '*';
signup.Visible = false;
}
private void signupbtn_Click(object sender, EventArgs e)
{
signup.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (unnew.Text != null && pwnew.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
else
{
MessageBox.Show("Error");
}
}
private void loginbtn_Click(object sender, EventArgs e)
{
if (untxt.Text != null && pwtxt.Text != null)
{
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM userTable where username = '" + untxt.Text + "' and password '" + pwtxt.Text + "'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form2 meLoad = new Form2();
meLoad.Visible = true;
this.Hide();
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Username or Password is incorrect");
}
obj.conn.Close();
MessageBox.Show("Successfully Login");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("No empty fields are allowed");
}
{
}
}
}
}
Hi, I am completely new to c#, im having this error whenever i click sign up. It tells me to check the line 44 which is
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string insertuser = "insert into userTable('" + unnew.Text + "', '" + pwnew.Text + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = insertuser;
obj.conn.Close();
MessageBox.Show("Signup has been completed");
signup.Visible = false;
}
Im a student, adn dont have enough background in programming, i'd appreciate someone's help. I really want to learn this programming language, and im currentlty having troubles.enter image description here Thank u so much.
I use this for Connection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
class Connect
{
public SqlConnection conn = new SqlConnection();
public SqlCommand cmd = new SqlCommand();
public string locate = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\hp\source\repos\WindowsFormsApp1\WindowsFormsApp1\UserDB.mdf;'Integrated Security=True";
}
}
It seems something is breaking to connect your database.
Please double check your connection string,If you need help for connection string, you may visit https://www.connectionstrings.com/
This tutorial may be helpful for you to connect database using c#.
https://www.guru99.com/c-sharp-access-database.html

method is not being called by application

My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
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;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}

c# : How to get data from database and pass to another form?

I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
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 EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.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;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}

store ID's in the database

i have a slight problem here,I have the following master tables
M_employee
EMPID Name
1 abc
2 xyz
M_Division
DIVID EMPID DIVISON
1 2 arts
2 1 science
M_Designation
DESGID EMPID Designation
1 2 Teacher
2 1 Scientist
and based on the ID's present in the master table i retrieve few fields on a label in a form....What i want to do is when i store these values of the form in a new table i want only the id's to be stored and not the text values which are being displayed in the label of the form.Below is the code I tried..Can anyone help me?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true");
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn);
cmd.Parameters.AddWithValue("#EMPID", Name);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn);
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
int cnt = cmd.ExecuteNonQuery();
conn.Close();
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
}
As requested, here is the idiomatic way of using using for IDisposable resources. Note, I've done nothing else with the code's logic but that, so pay attention to other answers :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#EMPID", Name);
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
int cnt;
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn))
{
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
conn.Open();
cnt = cmd.ExecuteNonQuery();
}
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
When you read in your division and designation, store the ids somewhere, like in a private filed of this class:
public partial class temporaryduty : System.Web.UI.Page
{
private int divisionId;
private int designationId;
...
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
divisionId = objDs.Tables[0].Rows[0]["Expr1"];
designationId = objDs.Tables[0].Rows[0]["Expr2"];
}
Then, on your button click use those fields to insert the ids:
cmd.Parameters.AddWithValue("#DIVID", divisionId);
cmd.Parameters.AddWithValue("#DesigID", designationId);

Response.Redirect Doesn't Work in my Windows Forms Application

My page does not redirect to the Page I have specified. While I am doing so it says The name "Response" does not exist in the current context
Please also help me with getting the register value in the database while doing the signup.
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;
namespace LoginSystem123
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
var myConnection = new SqlConnection();
myConnection.ConnectionString = #"Data Source=mukesh-PC\SQLEXPRESS;Initial Catalog=testDb;Integrated Security=True;Pooling=False";
var myCommand = new SqlCommand();
var cmd = "SELECT * FROM [User] Where [User].Email =" + "'" + textBoxEmail.Text + "'";
myCommand.CommandText = cmd;
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myConnection.Open();
var myReader = myCommand.ExecuteReader();
bool isRegisteredUser = myReader.Read();
if (isRegisteredUser)
{
var PasswordFromDatabase = myReader.GetString(5);
if (textBoxPassword.Text == PasswordFromDatabase.TrimEnd())
{
MessageBox.Show("Successfully Logged on !");
}
else
{
MessageBox.Show("Invalid password. Try again");
}
}
else
{
MessageBox.Show("Invalid user");
}
}
/* private void buttonSignUp_Click(object sender, EventArgs e)
{
Response.Redirect("SignUp.cs");
}
*/
private void buttonSignUp_Click_1(object sender, EventArgs e)
{
Response.Redirect("SignUp.cs");
}
}
}
Response.Redirect is used to redirect to another page in an ASP website - nothing like this works in Windows Forms.
If SignUp.cs defines a Form, you can do something like this to show it:
var signup = new SignUp();
signup.ShowDialog();
If you let us know more about what you're trying to do, we can probably be a bit more helpful.
Response.Redirect only works for web applications, and it looks like you're coding for Windows application.
You should do this instead:
SignUp su = new SignUp();
su.Show();
this.Hide();

Categories