I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.
Related
I'm trying to get my application to work with the database which is online in a phpmyadmin sql server. when i start my application it needs to get the password from the database, but when it tries to open a connection the whole program just freezes and it stays like that for a long time. in each class in which i am using this i make a new connection i don't know if this could be a problem for this or not.
here underneath is the database class i am using for this.
class Database
{
private SqlConnection connection;
private string connectionstring = "Server=studmysql01.fhict.local;Uid=dbi413434;Database=dbi413434;Pwd=Koekjesdeeg;";
private string nfcId;
private int vak;
private int rij;
public Database()
{
connection = new SqlConnection(connectionstring);
}
public string GetPassword(string username)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT password FROM Login WHERE username = '" + username + "'", connection);
string checkPassWord = Convert.ToString(cmd.ExecuteScalar());
connection.Close();
return checkPassWord;
}
public void MakeAccount(string userName, string passWord)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO LOGIN (USERNAME, PASSWORD) VALUES (#USERNAME, #PASSWORD)";
comm.Parameters.AddWithValue("#USERNAME", userName);
comm.Parameters.AddWithValue("#PASSWORD", passWord);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("account is not made");
}
connection.Close();
}
public void Change_Info(double rate, int maximum_stay, int row, int line)
{
string command;
connection.Open();
SqlCommand comm = connection.CreateCommand();
if (rate == 0)
{
command = "UPDATE General SET Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
else if (maximum_stay == 0)
{
command = "UPDATE General SET Rate=#rate, Row=#row, Line=#line WHERE ID=1";
}
else if (row == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Line=#line WHERE ID=1";
}
else if (line == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row WHERE ID=1";
}
else
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
comm.CommandText = command;
comm.Parameters.AddWithValue("#rate", rate);
comm.Parameters.AddWithValue("#maximum_stay", maximum_stay);
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not updated in general");
}
connection.Close();
}
public void CheckForId(int id, int row, int line, bool taken, string target)
{
string queryUpdate = "UPDATE eventlog SET Rij=#row, Vak=#line, Beschikbaarheid=#taken, Parkeerdoel=#target WHERE ID=#id";
string queryInsert = "INSERT INTO eventlog (ID, Rij, Vak, Beschikbaarheid, Parkeerdoel) VALUES (#id, #row, #line, #taken, #target)";
string queryDelete = "DELETE * FROM eventlog WHERE id=#id";
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM eventlog WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", id);
string data = Convert.ToString(cmd.ExecuteScalar());
SqlCommand comm = connection.CreateCommand();
if (data == "")
{
comm.CommandText = queryInsert;
}
else if (Int32.Parse(data) == id)
{
comm.CommandText = queryUpdate;
}
else
{
comm.CommandText = queryDelete;
}
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
comm.Parameters.AddWithValue("#taken", taken);
comm.Parameters.AddWithValue("#target", target);
comm.Parameters.AddWithValue("#id", id);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not correctly inserted checkForid");
}
connection.Close();
}
public double GetRate()
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT Rate FROM General WHERE ID=1", connection);
double rate = Convert.ToDouble(cmd.ExecuteScalar());
connection.Close();
return rate;
}
public void SetId(int id, string nfcId, string kenteken, int row, int line, DateTime begintTijd)
{
if (row != -1 || line != -1)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO INCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", begintTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", row);
comm.Parameters.AddWithValue("#ParkeerVak", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not correctly inserted Setid");
}
connection.Close();
}
}
public void GetVisitorInformation(string kenteken)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT NfcId FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd2 = new SqlCommand("SELECT ParkeerVak FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd3 = new SqlCommand("SELECT ParkeerRij FROM INCHECK WHERE Kenteken=#kenteken", connection);
cmd.Parameters.AddWithValue("#kenteken", kenteken);
cmd2.Parameters.AddWithValue("#kenteken", kenteken);
cmd3.Parameters.AddWithValue("#kenteken", kenteken);
nfcId = Convert.ToString(cmd.ExecuteScalar());
vak = Convert.ToInt32(cmd2.ExecuteScalar());
rij = Convert.ToInt32(cmd3.ExecuteScalar());
connection.Close();
}
public void SetCheckOutId(int id, string kenteken, DateTime eindTijd)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO UITCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", eindTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", rij);
comm.Parameters.AddWithValue("#ParkeerVak", vak);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("checkoutid is not correctly inserted");
}
connection.Close();
}
public void SetParkingTargets(string target)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO ParkingTargets (Targets) VALUES (#Targets)";
comm.Parameters.AddWithValue("#Targets", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("parking targets are not set");
}
connection.Close();
}
public void DeleteParkingTarget(string target)
{
string queryDelete = "DELETE FROM ParkingTargets WHERE Targets=#target";
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = queryDelete;
comm.Parameters.AddWithValue("#target", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not deleted");
}
connection.Close();
}
public List<string> GetParkingTargets()
{
List<string> targets = new List<string>();
connection.Open();
SqlCommand cmd2 = new SqlCommand("SELECT COUNT(id) FROM ParkingTargets", connection);
int numberOfLines = Convert.ToInt32(cmd2.ExecuteScalar());
for (int i = 1; i <= numberOfLines; i++)
{
SqlCommand cmd = new SqlCommand("SELECT Targets FROM ParkingTargets WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", i);
targets.Add(Convert.ToString(cmd.ExecuteScalar()));
}
connection.Close();
return targets;
}
}
Iam trying to insert integer value into access database but its giving me Object cannot be cast from DBNull to other types. error but in datagridview im putting a value but still show me this error
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability =Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value);
if (dataGridView1.IsCurrentRowDirty)
{
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name",Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The "pencil" indicates that the row is being edited, thus - even with an entered value of 2 - the value of Availability can very well be null.
So your concept seems faulty; you should not attempt to insert data when dataGridView1.IsCurrentRowDirty is true but when it is false.
Finally got a solution on this i change my code dataGridView1_RowLeave to dataGridView1_CellValueChanged and its working fine
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
med_id = dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString();
if (med_id == "")
{
med_id1 = 0;
}
else
{
med_id1 = Convert.ToInt32( dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString());
}
if (med_id1 == 0)
{
try
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name", Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
catch (Exception ex)
{
}
}
else
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd = con.CreateCommand();
cmd.CommandText = "update Medicine_Available_Detail set Medicine_Name='" + dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString() + "',Dealer_name='" + dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString() + "',Availability='" + Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString())+ "'where Med_id=" + med_id1 + "";
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Updated Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
}
hi i have a login system that needs to go to multiple pages.
3 pages baroverzicht,keukenoverzicht,tafeloverzicht. if i login i go to tafeloverzicht with all users. i dont know how to fix it i just start coding
SQL server i have a table: Personeel
naam:----
password:----
afdelling: bar, keuken, bediening
bar needs to go to baroverzicht keuken needs to go to keukenoverzicht
bediening needs to go to tafeloverzicht
private void button1_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager
.ConnectionStrings["ReserveringenConnectionStringSQL"]
.ConnectionString;
SqlConnection conn = new SqlConnection(connString);
//----
//sql datbase connectie
//----
conn.Open();
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn);
tabel personeel(wachtwoord) op de vragen
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if (count ==1)
{
MessageBox.Show("OK");
this.Hide();
tafeloverzicht tafeloverzicht = new tafeloverzicht();
tafeloverzicht.Show();
}
else if (count > 0)
{
MessageBox.Show("");
}
else
{
MessageBox.Show("wachtwoord niet corect");
}
textBox1.Clear();
conn.Close();
}
}
}
Next to your question there are some other things to take into account:
a. Always use Parameters when creating Sql:
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord = #Password", conn);
cmd.Parameters.Add("#Password", password)
b. Put your database methods in a separate class (Encapsulation, etc.) --> example: ReserverationsDataAccess
c. To answer your main question we'll need some more info (see comments).
i have made some changes to the code now.
SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr = cmd.ExecuteReader();
int count = 0;
while(dr.Read())
{
count += 1;
}
if (count ==1)
{
SqlCommand cmd1 = new SqlCommand("select afdeling from personeel where wachtwoord =" + textBox1.Text + "", conn);
SqlDataReader dr1 = cmd1.ExecuteReader();
MessageBox.Show("OK");
if (dr1.Rows[0][0].ToString() == "keuken")
{
this.Hide();
keukenoverzicht keukenoverzicht = new keukenoverzicht();
keukenoverzicht.Show();
}
else if (dr1.Rows[0][0].ToString() == "bar")
{
this.Hide();
baroverzicht baroverzicht = new baroverzicht();
baroverzicht.Show();
}
else
{
this.Hide();
tafeloverzicht tafeloverzicht = new tafeloverzicht();
tafeloverzicht.Show();
}
}
else
{
MessageBox.Show("wachtwoord niet corect");
}
textBox1.Clear();
conn.Close();
}
}
it have now 2 errors on dr1.rows
-a-
what needs to be changed to fix the error (rows)
-b-
cmd.Parameters.Add("#Password", password) is for ****** in the textbox ride?
error rows
i'm creating a login form for my system and want to add a User and Admin account. what i did in my database is to create a table for my users with a specific user type U_Type would be either 1 = admin or 2 = user.
i want to add an if statement that would call my column name U_Type and compare it either 1 or 2. below is my unfinished code. i'm using visual studio 2008 c# and ms sql 2005
here is my code:
float Outcome;
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
conn.Open();
String txtUser = textBox1.Text;
String txtPass = textBox2.Text;
string query = "SELECT * FROM tblUsers WHERE U_Name=#U_Name AND U_Pass=#U_Pass AND U_Type=#type";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(new SqlParameter("#U_Name", txtUser));
cmd.Parameters.Add(new SqlParameter("#U_Pass", txtPass));
cmd.Parameters.Add(new SqlParameter("#type", type));
SqlDataReader dr = cmd.ExecuteReader();
if (textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (textBox2.Text.Trim().Length == 0)
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ()
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Login Failed");
Outcome = Convert.ToInt32(lblOutcome.Text);
Outcome = Outcome - 1;
textBox1.Clear();
textBox2.Clear();
lblOutcome.Text = Outcome.ToString();
if (Outcome == 0)
{
MessageBox.Show("You have reached the maximum number of trial");
this.Close();
}
}
}
i want the if statement to be here
else if (dr.HasRows == true)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);
con.Open();
SqlDataReader sdr = command.ExecuteReader();
if ("#type"==1)
{
MessageBox.Show("Login Successful");
MDIParent1 settingsForm = new MDIParent1();
settingsForm.Show();
this.Hide();
}
else
{
MessageBox.Show("Login Successful");
MDIParent2 settingsForm = new MDIParent2();
settingsForm.Show();
this.Hide();
}
}
i really don't know the proper syntax for it. help me please i would really appreciate it. thank you
You have, roughly, the right idea, but your implementation is off.
You're validating the text boxes after you send the SQL query but before you check the results, and you're also passing in the type of the user.
The user type should be stored in the database along with the user, and you can return the type of user for the matching row (based on username and password). And your syntax is way off in some places.
A simplified approach based on what you appear to be doing would be something like this:
Do validation on the text boxes before executing the command. If validation passes, then select the row that matches the user name and password, and process the results accordingly:
private void button1_Click(object sender, EventArgs e)
{
bool validInput = false;
if (!String.IsNullOrWhitespace(textBox1.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a user name.");
}
if (!String.IsNullOrWhitespace(textBox2.Text))
{
validInput = true;
}
else
{
MessageBox.Show("Please enter a password.");
}
if (validInput)
{
using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name = #U_Name AND U_Pass = #U_Pass", conn);
command.Parameters.Add("#U_Name", SqlDbType.VarChar).Value = textBox1.Text;
command.Parameters.Add("#U_Pass", SqlDbType.VarChar).Value = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
string userType = reader["U_type"].ToString();
if (userType == "1")
{
// Handle regular users
}
else if (userType == "2")
{
// Handle admin users
}
}
else
{
MessageBox.Show("Login failed.");
}
}
}
}
}
The above code illustrates the approach. If both text boxes have text in them, the validInput flag is set to true. The connection is then opened, the command and parameters are set, the command is executed and a reader returned. If the reader has rows (meaning 1 or more records that matched the username and password are found), the reader is advanced to the first record (there should be only one match for a given username/password combination).
The "U_type" column is interrogated to see if it's a regular user or an admin user, and the user is processed accordingly.
It's not clear from your posted code whether "U_type" is a string or an integer; if it's an integer you'll need to convert it like this:
int userType = Convert.ToInt32(reader["U_type"]);
And change the corresponding if checks:
if (userType == 1)
and
if (userType == 2)
If you want to authenticate user and compare the Type then return DataTable.
public DataTable ValidateUser(string username,string password)
{
DataTable dt = new DataTable();
SqlCommand cmd; SqlDataReader dr;
SqlConnection con = new SqlConnection(yourConnectionString);
try
{
cmd = new SqlCommand();
cmd.CommandText = "Select * from tblUsers where U_Name=#U_Name and U_Pass=#U_Pass";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#U_Name", username);
cmd.Parameters.AddWithValue("#U_Pass", password);
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
dr = cmd.ExecuteReader();
dt.Load(dr);
}
catch (Exception ex)
{
dt = null;
}
finally
{
if (con.State != ConnectionState.Closed)
{
con.Close(); con.Dispose();
}
}
return dt;
}
Calling ValidateUser Method:
DataTable dt=new DataTable();
dt=ValidateUser();
if(dt!=null && dt.Rows.Count>0)
{
if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==1)
{
//show form for user where utpe=1
}
else if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==2)
{
//show form for user where utype=1
}
else
{
//otherstuff
}
}
else
{
//invwalid user
}
hopethis helps
this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.