Reputation: 2233
I'm building a desktop application where the scenario is A user will be logged in and in another form it's id will be shown in text box.
But After user logged in I saw the error like this :
Here is my first form (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();
}
private 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");
SqlCommand command = new SqlCommand("select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'", connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'", connection);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
And Here is my Second form(Entry.cs) where I want to print the user id:
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(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
If anyone find out the problem..help me to find it out please!
Upvotes: 0
Views: 1728
Reputation: 3248
You need to open your sql connection instance first to make a query against sql server.
Change your code:
SqlConnection connection = new SqlConnection(@"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
SqlCommand command = new SqlCommand("select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'", connection);
//...
Upvotes: 2