so my idea was once user will be loged in it will add +1 to the other table and online value in my mysql. I have done code like it's bellow. Once I have debug. I have inserted username and password but once I have press login button it says Error Connection. I am sure I have did something wrong in code but cant get it sort. So am trying to get help from you guys. Thanks
private void loginBtn_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
con.Open();
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
MySqlCommand newcmd = new MySqlCommand("UPDATE company SET online = online + 1 WHERE name = '" + row["company"].ToString() + "'");
try
{
newcmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
con.Close();
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
return;
}
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
For your question, you have connection error when you log in.
The error may be that there is already an open data reader associated with this connection
which must be closed, so close the data reader connection.
You could try the following code to get it.
private void btn_Submit_Click(object sender, EventArgs e)
{
conn.Open();
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteScalar();
MySqlDataReader row;
row = cmd.ExecuteReader();
string company=null;
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
company = row["company"].ToString();
MessageBox.Show(row["company"].ToString(), "Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
row.Close();
cmd.CommandText = "UPDATE company SET online = online + 1 WHERE name = '" + company + "'";
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
finally
{
conn.Close();
}
}
Result:
Related
Im writing a code which is saving users from a program in sql tables but when 15 users in one time are saving or updating im getting 1 min delay and program not responding... Can you help me. Its my code.
public bool GetUser(ref clsConnection c)
{
try
{
MySqlConnection connect = new MySqlConnection(connectionMysql);
connect.Open();
MySqlCommand query = new MySqlCommand("SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'", connect);
query.Prepare();
MySqlDataReader dr = query.ExecuteReader();
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
dr.Close();
connect.Close();
return true;
}
}
public void UpdateUser(clsConnection u)
{
MySqlConnection cn = new MySqlConnection(connectionMysql);
try
{
if (u.Username != "")
{
cn.Open();
MySqlCommand query = new MySqlCommand(#"UPDATE Users SET User_Name=#User_Name,User_PlyName=#User_PlyName,User_Cash=#User_Cash,User_Passowrd=#User_Password WHERE User_Name='" + Escape(u.Username) + "';", cn);
if (query != null)
{
query.Parameters.AddWithValue("#User_Name", Escape(u.Username));
query.Parameters.AddWithValue("#User_PlyName", Escape(u.NoColPlyName));
query.Parameters.AddWithValue("#User_Cash", u.Cash);
query.Parameters.AddWithValue("#User_Passowrd", u.Password);
cn.Close();
return;
}
else
{
return;
}
}
}
}
public void AddUser(clsConnection c)
{
try
{
if (c.Username != "")
{
Query(#"INSERT INTO Users (User_Name,User_PlayerName,User_Cash,User_Passowrd) VALUES ('" +
Escape(c.Username) + "', '" +
Escape(c.NoColPlyName) + "', '" +
c.Cash + "', '" +
Espace(c.Passoword) + "');");
}
}
}
//when 15 users try to connect to program program not responding and delay is very big. When <10 users connected to program, program works good,but +10 delay is big...
You should put your query in a using statement like this:
using (MySqlConnection con = new MySqlConnection(connectionMysql))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM Users WHERE User_Name='" + Escape(c.Username) + "'";
using (MySqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
c.Username = dr[1].ToString();
c.NoColPlyName = dr[2].ToString();
c.Cash = double.Parse(dr[3].ToString());
c.Password = dr[4].ToString();
}
else
{
dr.Close();
connect.Close();
return false;
}
return true;
}
}
}
And then you can implement the same method to your UPDATE and INSERT queries
i have
if (Text == "Add Client") // TEXT IS THE FORM.TEXT
{
newClient = new Client();
stateList = StateDB.GetStateList();
stateComboBox.DataSource = stateList;
clientBindingSource.Clear();
clientBindingSource.Add(newClient);
}
and this is my properties
and here is insert statement
SqlConnection connection = PRG299DB.GetConnection();
string insertStatement =
"INSERT INTO Client " +
"(FirstName, LastName, BirthDate, StreetName, " +
"City, State, ZipCode, CellPhone) " +
"VALUES (#FirstName, #LastName, #BirthDate, #StreetName, " +
"#City, #State, #ZipCode, #CellPhone);";
SqlCommand insertCommand = new SqlCommand(insertStatement,
connection);
insertCommand.Parameters.AddWithValue("#FirstName",
client.FirstName);
insertCommand.Parameters.AddWithValue("#LastName", client.LastName);
insertCommand.Parameters.AddWithValue("#BirthDate", client.BirthDate);
insertCommand.Parameters["#BirthDate"].SqlDbType = SqlDbType.DateTime;
insertCommand.Parameters.AddWithValue("#StreetName", client.StreetName);
insertCommand.Parameters.AddWithValue("#City", client.City );
insertCommand.Parameters.AddWithValue("#State", client.State);
insertCommand.Parameters.AddWithValue("#ZipCode", client.ZipCode);
if (client.CellPhone == null)
insertCommand.Parameters.AddWithValue("#CellPhone", DBNull.Value);
else
insertCommand.Parameters.AddWithValue("#CellPhone", client.CellPhone);
try
{
connection.Open();
insertCommand.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Client') FROM Client";
SqlCommand selectCommand = new SqlCommand(selectStatement, connection);
int vendorID = Convert.ToInt32(selectCommand.ExecuteScalar());
return vendorID;
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
And the update statement
SqlConnection connection = PRG299DB.GetConnection();
string updateStatement =
"UPDATE Client SET " +
"FirstName = #NewFirstName, " +
"LastName = #NewLastName, " +
"BirthDate = #NewBirthDate, " +
"StreetName = #NewStreetName, " +
"City = #NewCity, " +
"State = #NewState, " +
"ZipCode = #NewZipCode, " +
"CellPhone = #NewCellPhone " +
"WHERE ClientID = #OldClientID " +
"AND FirstName = #OldFirstName " +
"AND LastName = #OldLastName " +
"AND Birthdate = #OldBirthDate " +
"AND StreetName = #OldStreetName " +
"AND City = #OldCity " +
"AND State = #OldState " +
"AND ZipCode = #OldZipCode " +
"AND (CellPhone = #OldCellPhone " +
"OR CellPhone IS NULL AND #OldCellPhone IS NULL)";
SqlCommand updateCommand = new SqlCommand(updateStatement, connection);
updateCommand.Parameters.AddWithValue("#NewFirstName", newClient.FirstName);
updateCommand.Parameters.AddWithValue("#NewLastName", newClient.LastName);
updateCommand.Parameters.AddWithValue("#NewBirthDate", newClient.BirthDate);
updateCommand.Parameters.AddWithValue("#NewStreetName", newClient.StreetName);
updateCommand.Parameters.AddWithValue("#NewCity", newClient.City);
updateCommand.Parameters.AddWithValue("#NewState", newClient.State);
updateCommand.Parameters.AddWithValue("#NewZipCode", newClient.ZipCode);
if (newClient.CellPhone == "")
updateCommand.Parameters.AddWithValue("#NewCellPhone", DBNull.Value);
else
updateCommand.Parameters.AddWithValue("#NewCellPhone", newClient.CellPhone);
updateCommand.Parameters.AddWithValue("#OldClientID", oldClient.ClientID);
updateCommand.Parameters.AddWithValue("#OldFirstName", oldClient.FirstName);
updateCommand.Parameters.AddWithValue("#OldLastName", oldClient.LastName);
updateCommand.Parameters.AddWithValue("#OldBirthDate", oldClient.BirthDate);
updateCommand.Parameters.AddWithValue("#OldStreetName", oldClient.StreetName);
updateCommand.Parameters.AddWithValue("#OldCity", oldClient.City);
updateCommand.Parameters.AddWithValue("#OldState", oldClient.State);
updateCommand.Parameters.AddWithValue("#OldZipCode", oldClient.ZipCode);
if (oldClient.CellPhone == "")
updateCommand.Parameters.AddWithValue("#OldCellPhone", DBNull.Value);
else
updateCommand.Parameters.AddWithValue("#OldCellPhone", oldClient.CellPhone);
try
{
connection.Open();
int count = updateCommand.ExecuteNonQuery();
if (count > 0)
return true;
else
return false;
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
i want to be able to have a display value of stateName and the selected value to be stateCode
for example: stateName: South Carolina and stateCode :sc
the error is that when i click the save. It don't save it to the database with the selected value :"sc" it saves with the display value "South Carolina"
i will really appreciate any hints or tips thanks in advance
if you need more code refer to this link
https://github.com/andakap99/ProjectPRG299DB/blob/master/WindowsFormsApplication1/frmAUI.cs
i needed to add a selected index changed event that looked like this
private void stateComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (newClient != null || newCompany != null || newSchool != null)
{
if (cliLVVisible)
{
newClient.State = (string)stateComboBox.SelectedValue;
}
else if (comLVVisible)
{
newCompany.State = (string)stateComboBox1.SelectedValue;
}
else if (schLVVisible)
{
newSchool.State= (string)stateComboBox2.SelectedValue;
}
}
}
I have a mysql left join query . This query runs ok . But the left joined table not getting values . Please go through below query . I am working in C#
void getstuinfo()
{
try
{
MySqlCommand com = new MySqlCommand("select stumaster.stuname,"+
"stumaster.lname,"+
"stumaster.fname,"+
"stumaster.mname,"+
"stumaster.fa_calty,"+
"stumaster.sex,"+
"castmaster.castdisp,"+
"stumaster.castcode,"+
"stumaster.nwscs "+
"from stumaster "+
" left join castmaster on stumaster.castcode = castmaster.castcode "+
" where grno = " + Convert.ToInt32(textBox1.Text).ToString(), con_db.con);
MySqlDataReader dr1 = com.ExecuteReader();
if (dr1.HasRows)
{
while (dr1.Read())
{
textBox2.Text = (dr1[("stuname")].ToString());
textBox4.Text = (dr1["lname"]).ToString();
textBox5.Text = (dr1["fname"]).ToString();
textBox6.Text = (dr1["mname"]).ToString();
comboBox5.Text = (dr1["fa_calty"]).ToString();
comboBox1.Text = (dr1["castdisp"]).ToString();
textBox7.Text = (dr1["castcode"]).ToString();
textBox9.Text = (dr1["nwscs"]).ToString();
string wsex = (dr1["sex"]).ToString();
if (wsex == "M")
{
radioButton1.Checked = true;
}
else
{
radioButton2.Checked = true;
}
}
dr1.Close();
}
else
{
MessageBox.Show("Not a Valid G.R.No.", " Student Information ");
dr1.Close();
textBox1.Focus();
return;
}
}
catch (FormatException)
{
MessageBox.Show("Date is Invalid ");
}
}
you have to give the table name with grno
ie
stumaster.grno = conditiion
In loggin comtrol I have ridrect the user to same url after login.In comment control when unregistered or unlogin user tries to comment I show him message which redirects hin in login control.Now I need to redirect him again back to comment page after login but I am in big dillema.
The following are my codes:
login.ascx.cs
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
txtPassword.Text = obj.Encrypt(txtPassword.Text.Trim(), true);
MySqlCommand cmd = new MySqlCommand("Select id,username,password From registration where username=#UserName And password= #password ", con);
cmd.Parameters.AddWithValue("#UserName", txtusername.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
//MySqlDataAdapter da1 = new MySqlDataAdapter("select id,username from registration where username='" + txtusername.Text + "'", con);
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
string message = null;
if (dt.Rows.Count > 0)
{
String t1 = dt.Rows[0]["id"].ToString();
String username = dt.Rows[0]["username"].ToString();
Session["UserId"] = t1;
Session["username"] = username;
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
if (MyUrl != null)
HttpContext.Current.Request.UrlReferrer.ToString();
string userName = Session["username"].ToString();
//pnllogin.Visible = false;
message = "Hello " + userName + ", Welcome to our website.";
//Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup1('" + message + "');", true);
}
else
{
message = "Sorry You cannot login, please provide correct Email and password";
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
}
comment.ascx.cs
protected void btncomment_Click(object sender, EventArgs e)
{
try
{
if (Session["userid"] != null)
{
main AddComment = new main();
string mandir_id = Request.QueryString["id"];
sQLcONN.Open();
string SQL2 = "insert into comment (user_id,Comment,with_temple) values ('" + Session["userid"] + "','" + txtComment.Text + "','" + mandir_id + "')";
sQLcONN.Close();
AddComment.saveData(SQL2);
Bindcomment();
}
else
{
//ModalPopupExtender1.Show();
// Response.Write("You Must Login Or Register To Comment");
// lblcommentmsg.Text="You Must Login Or Register To Comment";
string message = "You Must Login Or Register To Comment";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + message + "');", true);
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
Before actual redirection of unauthenticated users to the login page, why not introduce something like Session["returnPath"] = Request.RawUrl; and then when users get authenticated:
if (!string.IsNullOrWhiteSpace(Session["returnPath"]))
Response.Redirect(Session["returnPath"]);
Additionally, ASP.NET MVC uses a returnUrl URL parameter instead of a session valuable. So your login URL would look like: http://www.example.com/Login?returnUrl=/the-page-you-were-on.aspx. Seems to work well.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
C# having some errors from fetching
public partial class BioreCottonPurchaseSlip2011 : Form
{
Library obj = new Library();
public BioreCottonPurchaseSlip2011()
{
InitializeComponent();
}
public void enableDisableControls(bool flag)
{
TxtExtensionNo.Enabled = flag;
TxtFarmerCode.Enabled = flag;
TxtFarmerName.Enabled = flag;
TxtBasicPrice.Enabled = flag;
TxtPremium.Enabled = flag;
TxtWeight.Enabled = flag;
TxtTotalAmountBasic.Enabled = flag;
TxtTotalAmountPremium.Enabled = flag;
TxtBalancePay.Enabled = flag;
BtnSave.Enabled = flag;
BtnCancel.Enabled = flag;
}
public void clearControls()
{
TxtExtensionNo.Text = "";
TxtFarmerCode.Text = "";
TxtFarmerName.Text = "";
TxtBasicPrice.Text = "";
TxtPremium.Text = "";
TxtWeight.Text = "";
TxtTotalAmountBasic.Text = "";
TxtTotalAmountPremium.Text = "";
TxtBalancePay.Text = "";
}
private void BtnNew_Click(object sender, EventArgs e)
{
if (obj.GetConnection() == true)
{
lblError.Text = "Connected !!!";
}
else
{
lblError.Text = "Not connnected !!!";
}
enableDisableControls(true);
BtnNew.Enabled = false;
// lblError.Text = "";
string connectionString = "Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True";
string sql = "SELECT * FROM cottonpurchase";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds, "cottonpurchase");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "cottonpurchase";
}
private void BtnSave_Click(object sender, EventArgs e)
{
if (obj.GetConnection() == true)
{
//dateTimePicker1.Value = DateTime.Today;
MessageBox.Show("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + ")");
if (obj.ExecuteSQLStatement("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + " )") == true)
{
lblError.Text = "Item(s) Saved";
clearControls();
BtnSave.Enabled = false;
BtnNew.Enabled = true;
enableDisableControls(false);
}
else
{
lblError.Text = "Item(s) Not Saved";
}
}
else
{
lblError.Text = "Connection Error. Please contact your administrator.";
}
enableDisableControls(false);
clearControls();
BtnNew.Enabled = true;
try
{
//double getvat = 0;
//double calculatevat = 0;
//getvat = Convert.ToDouble(TxtTotalAmountBasic.Text);
//calculatevat = getvat * 0.18;
//TxtBasicPrice.Text = calculatevat.ToString();
//TxtBasicPrice.Enabled = false;
}
catch (Exception)
{
// lblError.Text = "Please contact your administrator. (Error - TARS0001DATMIS)";
clearControls();
enableDisableControls(false);
BtnNew.Enabled = true;
//lblInvoiceNo.Text = "INVOIC NO";
}
}
private void BtnCancel_Click(object sender, EventArgs e)
{
enableDisableControls(false);
clearControls();
BtnNew.Enabled = true;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void TxtFarmerCode_TextChanged(object sender, EventArgs e)
{
try
{
SqlConnection conn= new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
conn.Open();
cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=#aa", conn);
cmd.Parameters.Add("#aa", SqlDbType.Int).Value = TxtFarmerCode.Text;
dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
// textBox1.Text = dr[0].ToString(); Since U r going to give the ID and retrieve in textBox1.
TxtFarmerName.Text = dr[0].ToString();
//textBox3.Text = dr[1].ToString();
//textBox4.Text = dr[2].ToString();
//textBox7.Text = dr[3].ToString();
//dateTimePicker1.Text = dr[4].ToString();
//dateTimePicker2.Text = dr[5].ToString();
//textBox5.Text = dr[6].ToString();
}
}
catch
{
// lblError = "THE GIVEN ID IS UNAVAILABLE";
}
finally
{
conn.Close();
}
}
}
You have to define your variable types
SqlCommand cmd = new SqlCommand(...);
SqlReader dr = cmd.ExecuteReader();
In TxtFarmerCode_TextChanged, you haven't defined the variables cmd or dr.
You'll want something like this:
SqlCommand cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=#aa", conn);
[...]
SqlDataReader dr = cmd.ExecuteReader();