I have a button that when pressed, looks for a value based on a listbox choice and if it finds records in the table, it takes that value from listbox and puts it into a session, refreshes the page and the session is then used as a data source, ie. find where session = session.
Now what happens is if i want to do two consecutive searches, the button doesnt store new session, instead it takes the old session. So if I search for x first, then y, it will add x when page is refreshed.
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
JourOrigin.SelectedValue = null;
}
else
{
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
}
con.Close();
}
I managed to clear the session if there is a session already, but I have to press value twice to store it. Is it possible to "refresh" a session every time the button is pressed?
You must try this code:
protected void search(object sender, EventArgs e)
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Driver WHERE City = '" + JourOrigin.SelectedItem + "' ";//retrieves driver names from table
dr = cmd.ExecuteReader();
dr.Read();
if(Session["city"] != null)
{
Session["city"] = null;
}
if(dr.HasRows)
{
Session["city"] = JourOrigin.SelectedItem.ToString();
Response.Redirect("~/Account/FindDriver.aspx");
NoCity.Visible = false;
}
else
{
DriversJourney.Items.Clear();
DriversJourney.Items.Add("No Drivers in selected city, try another city");
NoCity.Visible = true;
NoCity.Text = "No drivers in selected city, please try another city";
}
con.Close();
}
Related
So I have this DataGridView on which there are two columns which I am retrieving from my SQL Server database. Now, in the second column, we have a bit field which shows as a CheckBox in my Windows Application designer. So, I want to, on CellContentClick event be able to update the value that just got deselected into my database. But seems like I am going nowhere.
Here is my code below:
private void gvTurnOffNotifications_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
bool result = Convert.ToBoolean(row.Cells[1].Value);
if (result == true)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
int temp = 1;
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where AllowNotification='" + false+ "'";
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
And then when I click on my "Update" button, I want to send the updated griddata for storing in my database as below:
private void btnUpdateTurnOff_Click(object sender, EventArgs e)
{
myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
mySQLDataAdapter = new SqlDataAdapter("spGetAllUpdatedNotifications", mySQLConnection);
mySQLDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
DataSet ds = new DataSet();
mySQLDataAdapter.Fill(ds);
mySQLDataAdapter.UpdateCommand = mySQLCommand;
mySQLDataAdapter.Update(ds);
}
}
The spGetAllUpdatedNotifications object in my Update block is a stored procedure I am calling just to retrieve the records from the database so I can update them on the fly in my DataSet. Here is the definition below:
create proc spGetAllUpdatedNotifications
as
begin
SELECT UserName, AllowNotification FROM UsersNotified where AllowNotification=1
end
GO
For more context: When my form loads, I am selecting all the records from the database which have their AllowNotification field set to bit 1 (true in C#) and once a user unticks a specific user (in other words, that user would not be allowed to receive notifications anymore) and once I click on the Update button, it should set the property to false (bit 0 in the database).
Instead of updating the one record which I have deselected, it updates all of them. "All" in this case are the records which have AllowNotification=1. I only want to set AllowNotification=0 for the deselected/unchecked record only
Any suggestions on how I can go about achieving this?
I am not sure what logic makes you to loop thru all the rows of the DataGridView just to update one row in the database.
If you want to update AllowNotification value for the username for which checkbox is checked or unchecked the logic would be this.
Figure out the updated value of the checkbox which is clicked in the gridview.
Store the updated value (True or False) in a boolean variable.
Retrieve the corresponding username of from the other cell of the same row the gridview.
Execute update query with criteria "WHERE UserName = {userName}".
You need to write CellContentClick event of the DataGridView as following.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1) //Assuming Checkbox is displayed in 2nd column.
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
var result = this.dataGridView1[e.ColumnIndex, e.RowIndex].Value;
var userName = this.dataGridView1[0, e.RowIndex].Value; //Assumin username is displayed in fist column
var connectionString = "Your Connection String";
//Set value of your own connection string above.
var sqlQuery = "UPDATE UsersNotified SET AllowNotification = #allowNotification WHERE UserName = #userName";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sqlQuery, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#allowNotification", SqlDbType.Bit).Value = result;
command.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = userName;
connection.Open();
command.ExecuteNonQuery();
}
}
}
}
This should help you resolve your issue.
I have a partial solution (It doesn't work a 100% but at least its a step in the right direction):
private void gvTurnOffNotifications_SelectionChanged(object sender, EventArgs e)
{
if (gvTurnOffNotifications.SelectedCells.Count > 0)
{
int selectedrowindex = gvTurnOffNotifications.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = gvTurnOffNotifications.Rows[selectedrowindex];
getUserSelected = Convert.ToString(selectedRow.Cells["UserName"].Value);
MessageBox.Show(getUserSelected);
foreach (DataGridViewRow row in gvTurnOffNotifications.Rows)
{
DataGridViewCheckBoxCell cell = row.Cells[1] as DataGridViewCheckBoxCell;
//We don't want a null exception!
if (cell.Value != null)
{
//It's checked!
btnUpdateTurnOff.Enabled = true;
myConnectionString = ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString;
using (mySQLConnection = new SqlConnection(myConnectionString))
{
bool change = false;
string procedureName = "update UsersNotified Set AllowNotification='" + change + "' where UserName='" + getUserSelected + "'";
//MessageBox.Show(cell.Value.ToString());
mySQLCommand = new SqlCommand(procedureName, mySQLConnection);
mySQLCommand.CommandType = CommandType.Text;
mySQLCommand.Connection = mySQLConnection;
mySQLCommand.Connection.Open();
mySQLCommand.ExecuteNonQuery();
}
}
}
}
}
Problem is that it just takes the first row without me having selected the row I want to deselect.
here is my login button click code. i have set the session["Username"] to the input of the customer in txtUser.text.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
and here is where i call it. (ordernow.aspx) this is where the customer is redirected when he/she places and order. im planning to pass the values of the customer (email address username phone number) into the textboxes before submitting the order.
private void GetMyCart()
{
DataTable dtProducts; // declare data table = dtProducts.
if (Session["MyCart"] != null) // check whether session is null or not.
{
dtProducts = (DataTable)Session["MyCart"]; //if session is not null, assign all session to dtproducts.
}
else
{
dtProducts = new DataTable(); //if session is null, create new datatable (dtproducts).
}
if (dtProducts.Rows.Count > 0) // if rows.count is greater than 0, it means there is a value records from the session.
{
txtCustomerName.Text = Session["Username"].ToString();
//txtCustomerPhoneNo.Text = Session["Contact"].ToString();
//txtCustomerEmailID.Text = Session["Email"].ToString();
//txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
txtTotalProducts.Text = dtProducts.Rows.Count.ToString(); // this will display all of the chosen records
btnIslandGas.Text = dtProducts.Rows.Count.ToString();
dlCartProducts.DataSource = dtProducts;
dlCartProducts.DataBind();
UpdateTotalBill();
pnlMyCart.Visible = true;
pnlCheckOut.Visible = true;
pnlEmptyCart.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
}
else // session is empty
{
pnlEmptyCart.Visible = true; // since session is empty and there is no value record, pull up the empty shopping cart page
pnlMyCart.Visible = false;
pnlCheckOut.Visible = false;
pnlCategories.Visible = false;
pnlProducts.Visible = false;
pnlOrderPlaceSuccessfully.Visible = false;
dlCartProducts.DataSource = null;
dlCartProducts.DataBind();
txtTotalProducts.Text = "0"; // total products, price and number logo is set to 0.
txtTotalPrice.Text = "0";
btnIslandGas.Text = "0";
}
the Session["Username"] is working. meaning it is binded with the txtCustomername.text. but the rest are not working (email,address,phone no.)
As I understand, what you are doing is that on your login page in case the user is authenticated i.e in your code when the passwords are successfully matched. The Session variables viz. Contact, Email, DeliveryAddress are not set at all. Only Name is set.
After this you make redirection to ordernow.aspx page. Hence you don't get them there. You only get one you set.
In register page you set the other Session variables but you have to understand that it's only after that they will be available in ordernow.aspx
So if you go from register to ordernow.aspx you will get the values but not when you go from login page to ordernow.aspx
You need to set the other Session variables as well in the Login page before making redirection to the ordernow page and accessing them there.
Update:
You are only getting password from the database on the basis of the username, but instead you need to get the whole user record with other details like email, contact , address as well. Then match the password, if it matches you have your user and all his other details with which you need to set Session variables.
Update Second:
if (temp == 1)
{
conn.Open();
string checkPassword = "select * from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
using (SqlDataReader oReader = passCom.ExecuteReader())
{
while (oReader.Read())
{
if(oReader["UserName"].ToString().Replace(" ", "") == txtPassword.Text.Trim())
{
Session["Username"] = oReader["FirstName"].ToString();
Session["Contact"] = oReader["Contact"].ToString();
Session["Email"] = oReader["Email"].ToString();
Session["DeliveryAddress"] = oReader["DeliveryAddress"].ToString();
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
break;
}
}
myConnection.Close();
}
}
I want to get the values from MySQL database and that would need to show the messages according to values. But it does not happen and that will always show int privilege is 0. If I did not assign that default value, errors will be showing on the code.
How can I solve this issue and show messages according to the int privilege values?
private void button_login_Click(object sender, RoutedEventArgs e)
{
string username = usernameInput.Text;
string password = passwordInput.Password;
int privilege = 0;
try
{
//This is command class which will handle the query and connection object.
string Query = "SELECT`tbl_user_login`.`u_id`,`tbl_user_login`.`u_username`,
`tbl_user_login`.`u_password`,`tbl_user_login`.`u_privilege`
FROM `bcasdb`.`tbl_user_login`WHERE `tbl_user_login`.`u_username` = '"
+ username + "' AND `tbl_user_login`.`u_password` ='" + password
+ "' AND `tbl_user_login`.`u_privilege` = #privi;";
MySqlConnection conn =
new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.Parameters.AddWithValue("#privi", privilege);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();
// Here our query will be executed and data saved into the database.
if (MyReader.HasRows && this.Frame != null)
{
while (MyReader.Read())
{
if (privilege == 1)
{
DisplayMsgBox("click ok to open the admin page ", "OK");
}
if (privilege == 2)
{
DisplayMsgBox("click ok to open the staff page ", "OK");
}
else
{
DisplayMsgBox("privilege 0", "ok");
}
}
}
else
{
DisplayMsgBox("sucess else", "ok");
}
conn.Close();
}
catch (Exception )
{
DisplayMsgBox("sucess catch", "ok");
}
}
Looks like what you're trying to do is checking the value of u_privilege column from tbl_user_login table instead of making a where condition based on privilege. You need to remove this where condition
AND `tbl_user_login`.`u_privilege` = #privi
and also remove the parameter assignment
cmd.Parameters.AddWithValue("#privi", privilege);
You can get the value of tbl_user_login.u_privilege by using MySqlDataReader.GetInt32 syntax inside while (MyReader.Read()) block
MyReader.GetInt32(3)
Please note that 3 is used because MyReader.GetInt32 requires a zero based index parameter and tbl_user_login.u_privilege is the fourth column from your query. The value should be assigned to privilege variable as below
privilege = MyReader.GetInt32(3)
On a side note, you should parameterize your query to avoid SQL injection. Here's the complete code after implementing the above changes
int privilege = 0;
try
{
//This is command class which will handle the query and connection object.
string Query = "SELECT`tbl_user_login`.`u_id`,`tbl_user_login`.`u_username`,
`tbl_user_login`.`u_password`,`tbl_user_login`.`u_privilege`
FROM `bcasdb`.`tbl_user_login`WHERE `tbl_user_login`.`u_username` =
#username AND `tbl_user_login`.`u_password` = #password;";
MySqlConnection conn =
new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
MySqlDataReader MyReader;
conn.Open();
MyReader = cmd.ExecuteReader();
// Here our query will be executed and data saved into the database.
if (MyReader.HasRows && this.Frame != null)
{
while (MyReader.Read())
{
privilege = MyReader.GetInt32(3)
if (privilege == 1)
{
DisplayMsgBox("click ok to open the admin page ", "OK");
}
if (privilege == 2)
{
DisplayMsgBox("click ok to open the staff page ", "OK");
}
else
{
DisplayMsgBox("privilege 0", "ok");
}
}
}
else
{
DisplayMsgBox("sucess else", "ok");
}
conn.Close();
}
catch (Exception )
{
DisplayMsgBox("sucess catch", "ok");
}
If im not wrong, the privilege is being returned as a string type. Try take it in as a string then cast it to an integer?
i am working on an sale invoice in sale invoice i am auto filling the data about product in its relevant fields, like when user enters product code in product code text box the product name and product price text boxes automatically fills themselves by retrieving data from DB, i want that when user starts type code here the program give the suggestions about all the products in the database. like when user enter 1 the program give suggestion about product codes, product codes starting with 1 show themselves and the user just selects the one he wants to.
the code I've done on text change event of product code text box is
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (txtProductCode1.Text == "")
{
txtProductName1.Text = "";
txtQty.Text = "";
txtSalePrice.Text = "";
txtTotal.Text = "";
}
string sql = "select productprice, ProductName";
sql += " from dbo.productlog";
sql += " where productCode = '" + txtProductCode1.Text + "'"; // Placing ProductCode in single quotes because it's not an int column, but a varchar column, in SQL server
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
if (sdr.Read())
{
txtProductName1.Text = sdr["ProductName"].ToString();
txtSalePrice.Text = sdr["ProductPrice"].ToString();
}
else if (txtProductName.Text == "")
{
goto exitPoint;
}
else if (!sdr.Read())
{
MessageBox.Show("Data not found", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
txtProductName.Focus();
}
exitPoint:
sdr.Close();
rs = null;
cn.Close();
}
how can i show suggestion about product codes in text box?
EDIT:
Its no a windform app means it's a desktop based app and i am creating it in C#.net using VS2010
check this , hope this will work for you
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletemode%28v=vs.110%29.aspx
I am using Microsoft SQL Server and Visual Studio-C# 2010 Ultimate.
I have a ListView and some items in it. I want to delete an item when I selected it and I clicked the button but I could not write the SqlCommandtext and I could not find the select event for ListView.
Deleting selected data from database using listview c#
private void btnlvdeleterow_Click(object sender, EventArgs e)
{
foreach (int i in Listview2.SelectedIndices)
{
string test = Listview2.Items[i].Text;
Listview2.Items.Remove(Listview2.Items[i]);
SQLiteCommand conn = new SQLiteCommand();
conn.Connection = DbClass1.GetConnection();
string del = "delete from UserData where UserName='" + test + "'";
int result=dbclass1.ExecuteAndReturn(del);
}
}
There is a SelectedIndex property available with the ListView. When you click the button, pass this index and then your Sql query will be something like
delete from Products where ProductID = 'obj.ID' where obj is obtained from listView.SelectedIndex
protected void listview1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
//This retrieves the selected row
ListViewItem item= listview1.Items [e.ItemIndex];
// Fetch the control for ProductId using findControl
int productId=int.Parse((item.Findcontrol("ProductID") as TextBox).Text);
//then use this column value in your sqlcommand
using( SqlCommand cmd = new SqlCommand
("delete from Products where ProductID=#ProductId", connection ))
{
command.Parameters.Add(new SqlParameter("ProductId", productId));
//Then execute the query
}
}
try
{
for (int j = 0; j <= listView2.Items.Count - 1; j++)
{
string test = listView2.SelectedItems[j].SubItems[1].Text;
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=root";
string Query = "delete from TABLE_NAME where COL_NAME='" + test + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
MyConn2.Close();
MessageBox.Show("Data Deleted");
// txtCustomerName.Text = test;
//listView2.Items.Remove(listView2.Items[i]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The Event you are looking for should be ListView.ItemSelectionChanged
where the eventArgs contains the selected Items