Need Help,There's no error but can't go to another form for this multi user form code(c#) [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm new to coding,and i need help with the code. There's no error found,and the program is running . but can't go to another form either Supervisor or Cashier, and I also found this in my debug output: A first chance exception of type System.Data.SqlClient.SqlException occurred in System.Data.dll
errorSystem.Data.SqlClient.SqlException (0x80131904).
SqlConnection myCon = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\Desktop\Assignment_IOOP\Assignment_IOOP\LoginDB.mdf;Integrated Security=True");
public string UserType;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
trydb();
}
private void trydb() {
try
{
SqlDataAdapter MyDataAdapter = new SqlDataAdapter("select * from Logindata where username '" +Usertext.Text+ "' and password '" +Passtext.Text+"' ;", myCon);
DataTable logicaldb = new DataTable();
MyDataAdapter.Fill(logicaldb);
int count = logicaldb.Rows.Count;
if (count > 0)
{
UserType = logicaldb.Rows[0][4].ToString();
if (UserType == "Supervisor")
{
Manage_Product spv = new Manage_Product();
spv.Show();
this.Hide();
}
else if (UserType == "Cashier")
{
Cashier csh = new Cashier();
csh.Show();
this.Hide();
}
else
{
MessageBox.Show("Unknown User Type");
}
}
}
catch (Exception a) {
Console.Write("error" + a.ToString());
}

The Error is because you haven't open the connection before using it. First open the connection with the line "myCon.Open();" before using it in SqlDataAdapter and then use the '=' operator in the select query of the where clause. you have missed that too in your query.
Your code should be
private void trydb() {
try
{
myCon.Open();
SqlDataAdapter MyDataAdapter = new SqlDataAdapter("select * from Logindata where username ='" +Usertext.Text+ "' and password ='" +Passtext.Text+"' ;", myCon);
DataTable logicaldb = new DataTable();
MyDataAdapter.Fill(logicaldb);
//rest of your code here
}
catch
{
//exception code here
}
}

Related

why is my code not evaluating the statements? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed yesterday.
Improve this question
private void button2_Click(object sender, EventArgs e)
{
string connectionString = "server=Hosam; database=Login; Integrated security=true";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select recive from logmain",con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
string check = reader.GetString(0);
MessageBox.Show("this is"+check);
string doc = "doctor";
if (check==doc)
{
doctorform1.Visible = true;
laboratoryform1.Visible = false;
registration1.Visible = false;
nurseform1.Visible = false;
}
else if(check!=doc)
{
MessageBox.Show("You don't have acess");
}
}
con.Close();
It's always returning you don't have access even when the statement is true
I have tried to change the data type to var

index was out of range. must be nonnegative and less than the size of the collection. parameter name: index [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Guys I really need for your help. I am getting an error for the above title. All trying to do is when datagridview is click it should display selected record into the text box as well as open it new form. Here is my code.
using System.Data;
using System.Data.SqlClient;
namespace DataGridview
{
public partial class FrmDataGrid : Form
{
SqlConnection con = new SqlConnection("ConnectionString");
public FrmDataGrid()
{
InitializeComponent();
}
private void FrmDataGrid_Load(object sender, EventArgs e)
{
try {
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM UserData";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[1].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[2].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[3].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[4].Cells["UserRole"].Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
FrmUpdate FormUpdate = new FrmUpdate();
FormUpdate.ShowDialog();
}
}
}
You're trying to fetch 5 rows without even checking that 5 rows exists in the result of your db query. I think you're trying to fetch 5 columns of a row, so use the following code for your requirement:
textBox1.Text = dataGridView1.SelectedRows[0].Cells["UserID"].Value.ToString();
textBox2.Text = dataGridView1.SelectedRows[0].Cells["FullName"].Value.ToString();
textBox3.Text = dataGridView1.SelectedRows[0].Cells["Username"].Value.ToString();
textBox4.Text = dataGridView1.SelectedRows[0].Cells["UserPassword"].Value.ToString();
textBox5.Text = dataGridView1.SelectedRows[0].Cells["UserRole"].Value.ToString();
You are most likely selecting a row that is out of range, during one of these calls:
dataGridView1.SelectedRows[0]

C# how would i add basic validation to my application, so that it displays a messagebox for when incorrect username or passwords are entered [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have connected a sql database to my windows form application in C# visual studio 2012, the database contains one table with three columns for Username, Password and Role.
Picture of my Table
Inside the table is data for username and password, there is also two user types in the role column which determine the form you will be directed to when logging in depending on whether your role is an admin or client.
picture of the data in my form
I now have the code for the login form so that it can detect whether a user is an admin or client when logging in but the problem is that i have no username and password validation which displays a messagebox detailing when a user has entered incorrect information.
Could someone please adapt my code so that it displays a messagebox showing that the user has entered an incorrect username or password if they have unsuccessfully tried to log in.
Here is my code below
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Role from Login Where UserName='" + textBox1.Text + "' and Password='" + textBox2.Text + "' ",con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count == 1)
{
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["Role"] as string)
{
case "Admin":
{
this.Hide();
AdminMenu ss = new AdminMenu();
ss.Show();
break;
}
case "Client":
{
this.Hide();
MenuForm mf = new MenuForm();
mf.Show();
break;
}
default:
{
// ... handle unexpected roles here...
break;
}
}
}
}
}
private void Login_Load(object sender, EventArgs e)
{
}
private void Login_FormClosing(object sender, FormClosingEventArgs e)
{
Application.ExitThread();
}
}
}
You just need to put a else condition in this case like this
else
{
MessageBox.Show("Login Details are incorrect.");
}
and also I am unable to understand why do you have to if condition like this
if(dt.Rows.Count == 1)
{
if (dt.Rows.Count == 1)
{
Whereas only first one could serve your purpose.
So the code would look something like this
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Data.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Role from Login Where UserName='" + textBox1.Text + "' and Password='" + textBox2.Text + "' ",con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count == 1)
{
switch (dt.Rows[0]["Role"] as string)
{
case "Admin":
{
this.Hide();
AdminMenu ss = new AdminMenu();
ss.Show();
break;
}
case "Client":
{
this.Hide();
MenuForm mf = new MenuForm();
mf.Show();
break;
}
default:
{
MessageBox.Show("Please contact your administrator");
break;
}
}
}
else
{
MessageBox.Show("Login Details are incorrect.");
}
}
Now if the case is where it is neither a Client nor a Admin you can just show a MessageBox.
And definitely your code need to be prevent from SQL injection

using datagridView, exception occurs for INSERT command, while deletion and updation are working perfectly in C# using access database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Using save button in my form, all operations (update, delete) working perfectly except INSERT command. Help me out of this...
public partial class frmeditaccess : Form
{
string table = "master";
OleDbDataAdapter da;
OleDbCommandBuilder cb;
DataTable dt;
OleDbConnection conn;
string query;
public frmeditaccess()
{
InitializeComponent();
}
private void btload_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data source= C:\Users\ViPuL\Documents\Visual Studio 2010\Projects\feedback#MERI\feedback#MERI\bin\feedback.mdb";
query = string.Format("SELECT * FROM {0}", table);
da = new OleDbDataAdapter(query, conn);
dt = new DataTable();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
private void btsave_Click(object sender, EventArgs e)
{
try
{
cb = new OleDbCommandBuilder(da);
da.Update(dt); //here update, delete are working. Only, Insert throws exception of syntax error in INSERT command.
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
This may be due to reserved keyword used as column name, try by specifying QuotePrefix and QuoteSuffix as below
cb = new OleDbCommandBuilder(da);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
da.Update(dt);

How to give a proper error message [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
According to my code "Your Password Has Been Changed successfully!, Congratulations!" message is popping up even though the update is not worked. how can I give an error message if the update is not taken place(It seems there is an error in my update statement too..). Actually I couldn't imagine how to use the if statement here..
protected void Button1_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=localhost; database=e-learningsystem; uid=root; password=123;port=3307;");
connection.Open();
try
{
MySqlCommand cmd1 = new MySqlCommand("UPDATE student Set Password= '" + TextBox3.Text + "' WHERE UserName='" + TextBox1.Text + "' AND Password='"+TextBox2.Text+"'", connection);
cmd1.ExecuteNonQuery();
Response.Write(#"<script language='javascript'>alert('Your Password Has Been Changed successfully!, Congratulations!')</script>");
connection.Close();
}
catch (Exception ex)
{
Response.Write(#"<script language='javascript'>alert(ex.Message)</script>");
}
}
cmd1.ExecuteNonQuery() returns the number of rows affected. So if your query updates any record then it will return more than 0 rows (in this case 1 row of that particular user)
So try this
if(cmd1.ExecuteNonQuery()>0)
{
// successfull
}
else
{
// failure
}
and Please do not pass values like this in your query. Try using SqlParameter to pass the parameters in query to avoid Sql Injection.
Sachin's Answer give you the solution for your message box popup issue.
But Why you implement your own authentication mechanism? is there any reason not to use asp.net membership providers?
Assume you have good reason to that. But if you are implementing custom authentication check this Sample Membership Provider Implementation
For example ChangePassword method :
public override bool ChangePassword(string username, string oldPwd, string newPwd)
{
// validate the user first, you are not doing any validation
// logged in user can change any other users password in your approach
if (!ValidateUser(username, oldPwd))
return false;
//new password validation and giving proper message if failed
// skip this code from given link
// use parameterized query as below
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
" SET Password = ?, LastPasswordChangedDate = ? " +
" WHERE Username = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#Password", OdbcType.VarChar, 255).Value = EncodePassword(newPwd);
cmd.Parameters.Add("#LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#Username", OdbcType.VarChar, 255).Value = username;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;
int rowsAffected = 0;
try
{
conn.Open();
// this is how you can check whether row updated or not
rowsAffected = cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
// you need to have proper error handling as well
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "ChangePassword");
throw new ProviderException(exceptionMessage);
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
if (rowsAffected > 0)
{
return true;
}
return false;
}

Categories