I have a username db table that I'm trying to connect with to compare the username/pass.
Here is my code, it's not working, what am I doing wrong?
DataTable dt = null;
protected void btn_Click_Login(object sender, EventArgs e)
{
string query = string.Format("SELECT * FROM Users WHERE Username='{0}' AND Password='{1}'", txtUsername.Text, txtPassword.Text);
using (SqlConnection c = new SqlConnection(ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter(query, c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
if (dt.Rows.Count > 0)
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
lblError.Text = "success";
}
else
{
lblError.Text = "Wrong Username/Password combination";
}
}
}
most probably you are using wrong datatable to check no of rows returned.
Check for t and dt instances of datatable.
Try creating a SqlCommand to hold your query.
SqlCommand cmd = new SqlCommand(query, c);
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
DataTable t = new DataTable();
a.Fill(t);
}
I'm not 100% sure that's your issue, but back in the days when i used to use ADO.NET (before L2SQL/EF, dark days indeed), i seem to remember an issue with DataTable's and SqlDataAdapter.
From what i remember - you can't fill a DataTable with a SqlDataAdapter based on a raw query string - you need to use SqlCommand. But i believe this can be accomplished with DataSet.
So either change to SqlCommand, or change to DataSet.
You fill t:
DataTable t = new DataTable();
a.Fill(t);
but read dt:
if (dt.Rows.Count > 0)
I decided to try the data reader and got it working:
protected void btn_Click_Login(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RbConnectionString"].ConnectionString);
conn.Open();
string queryString = "SELECT * FROM [Users] WHERE Username=#username AND Password= #password";
SqlCommand command = new SqlCommand(queryString, conn);
command.Parameters.AddWithValue("#username", txtUsername.Text);
command.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader reader = null;
reader = command.ExecuteReader();
if (reader.Read())
{
Session["Username"] = txtUsername.Text;
Session["Password"] = txtPassword.Text;
Response.Redirect("main.aspx");
}
else
{
lblError.Visible = true;
lblError.Text = "Incorrect Username/Password Combination";
}
conn.Close();
}
What error you are getting is not clear. But i feel your connection is open and is never closed. Try
c.Close();
Related
I want to return records on the basis of two parameters, EmployeeNo and Password. What i mean is that when a user enter his/her credentials like EmployeeNo and Password then first program check if its present in the database or not. But i have a problem with the datatable. Datatable has no rows. Following is my code, which seems Okay to me but i have no idea why its not working. Here is my code
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM TableUserProfile WHERE UserEmpNum=#UserEmpNum and UserPassword=#UserPassword", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserEmpNum", tbEmpNumber.Text);
cmd.Parameters.AddWithValue("#UserPassword", tbPassword.Text);
con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
cmd.ExecuteNonQuery();
if (dt.Rows.Count != 0)
{
if (cbRememberLogin.Checked)
{
Response.Cookies["UEmpNo"].Value = tbEmpNumber.Text;
Response.Cookies["UPass"].Value = tbPassword.Text;
Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(15);
Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(15);
}
else
{
Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(-1);
}
Session["UserEmployee"] = tbEmpNumber.Text;
Response.Redirect("~/UserProfile.aspx");
}
}
}
When i put my program on a debug mode, it retrieve nothing, Here is the pic
Here is my Database Table
Try this code
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.Connection = con;
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0 && dt != null)
{
gvr_rkit.DataSource = dt;
gvr_rkit.DataBind();
}
SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism.
he SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source. The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand . Fill method takes as its arguments a DataSet to be populated, and a DataTable object , or the name of the DataTable to be filled with the rows returned from the SelectCommand
This is my code inside my button Login Click. I would like to know How can I retrieve records from the database from the user that is currently logged in from any of the web forms that proceed the login form or what command do I insert into a select statement to be able to select the username of the current logged n user.
protected void btnLogin_Click(object sender, EventArgs e)
{
var CS = ConfigurationManager.ConnectionStrings["TupperwareDemAppConnString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
var cmd = new SqlCommand(#"SELECT * FROM [USER] WHERE userName= #txtUserName AND userPassword= #txtuserPassword ", con);
cmd.Parameters.Add(new SqlParameter("#txtUserName", txtUsername.Text));
cmd.Parameters.Add(new SqlParameter("#txtuserPassword", txtPassword.Text));
con.Open();
var sda = new SqlDataAdapter(cmd);
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count != 0)
{
if (CheckBox1.Checked)
{
Response.Cookies["UName"].Value = txtUsername.Text;
Response.Cookies["Pword"].Value = txtPassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddDays(15);
Response.Cookies["PWord"].Expires = DateTime.Now.AddDays(15);
}
else
{
Response.Cookies["UName"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["PWord"].Expires = DateTime.Now.AddDays(-1);
}
}
}
}
Store user id in any of the session variable (loggedInUserId) and passe it in where condition. you can get data into the datatable.
public void BindData()
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [USER] WHERE userId='+ loggedInUserId +'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
}
How can I adapt my code to any changes that are made remain persistent?
As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.
adb.Update(dt);
However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.
Code
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("#username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("#status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.
You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.
Or generate them with SqlCommandBuilder:
public static DataSet SelectSqlRows(string connectionString,
string queryString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);
//code to modify data in DataSet here
builder.GetUpdateCommand();
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);
return dataSet;
}
}
i'm writing a code on c# (winform). the program is about cachier and the database is
ms access.
when i am entering the data to the database it seems like the data was enterd but when i'm opening the ms access the table is empty. althogh, if i right click on the 'preview data set' in the visual studio, i can see the data.
here is my code so far regard to the database:
private void buttonCloseCart_Click(object sender, EventArgs e)
{
for (int i = 0; i < baught_items.Count; i++)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
connect.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Receipts (ItemName, Quantity, PricePerOne, Total) VALUES (#temp_item, #temp_item_quantity, #temp_item_price, #temp_total_item_price)", connect);
if (connect.State == ConnectionState.Open)
{
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20).Value = temp_item;
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20).Value = temp_item_quantity;
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20).Value = temp_item_price;
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20).Value = temp_total_item_price;
try
{
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Added To DataBase");
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
To get any rows back from your database storage through a OleDbDataAdapter you need to set its SelectCommand with a command that contains a SELECT statement
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
Actually you are using the same command used to INSERT data as it was the SelectCommand. Obviously it doesn't return records. You should have a duplicate record in your table.
I would change something to your code. If you have more than one record to add to your table (you have a loop there) then there is no sense in extracting data from your db at every loop. I would call the Fill of the table outside the loop. Also a bit performance gain could be obtained defining the OleDbCommand and its parameters just one time before entering the loop. Inside the loop just update the values of the parameters and call ExecuteNonQuery
private void buttonCloseCart_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\אורון\documents\visual studio 2012\Projects\CachierPro\CachierPro\CachierProDB.accdb";
connect.Open();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO Receipts
(ItemName, Quantity, PricePerOne, Total)
VALUES (#temp_item, #temp_item_quantity,
#temp_item_price, #temp_total_item_price)", connect);
cmd.Parameters.Add ("#temp_item", OleDbType.Char, 20);
cmd.Parameters.Add("#temp_item_quantity", OleDbType.Integer, 20);
cmd.Parameters.Add("#temp_item_price", OleDbType.Double, 20);
cmd.Parameters.Add("#cart_sum", OleDbType.Double,20);
for (int i = 0; i < baught_items.Count; i++)
{
string temp_item = baught_items[i].ToString();
int temp_item_quantity = baught_items_quantity[i];
double temp_item_price = baught_items_price[i];
double temp_total_item_price = total_items_price[i];
if (connect.State == ConnectionState.Open)
{
cmd.Parameters["#temp_item"].Value = temp_item;
cmd.Parameters["#temp_item_quantity"].Value = temp_item_quantity;
cmd.Parameters["#temp_item_price"].Value = temp_item_price;
cmd.Parameters["#cart_sum"].Value = temp_total_item_price;
try
{
int addedCount = cmd.ExecuteNonQuery();
if(addedCount == 0)
{
... problems here, record not added for some reasons
}
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = new OleDbCommand("SELECT * FROM Receipts", connect);
DataTable dt = new DataTable();
da.Fill(dt);
textBoxCurrentCartSumTXT.Clear();
textBoxPricePerOneTXT.Clear();
textBoxQuantityTXT.Clear();
textBoxSumForCurrentItemTXT.Clear();
connect.Close();
}
I have a main form (formMain) which loads a user control (classification) in its load event. And in the load event of the user control classification it displays a datagridview. Let me show you the code.
CLASSIFICATION
string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";
private void load_data()
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
Luckily it's working but when I click the search button located in another user control (search) it raises an event in the main form (formMain) wherein it must FILTER the datagridview in the user control (classification) but my code is not working.
Maybe I have a syntax error in my string query. Here is the code.
MAIN FORM
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
classification control = new classification();
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%#search'";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//MessageBox.Show(content.txtboxSearch.Text);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
use CONCAT()
string query = #"SELECT *
FROM tblclassification
WHERE class_name LIKE CONCAT('%', #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
try
"SELECT * FROM purchase_order.tblclassification WHERE class_name LIKE ('%#search%')";
or ..
"SELECT * FROM tblclassification WHERE (class_name LIKE '%#search%')"