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

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

Related

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

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
}
}

How to check if input exist in the database. ASP.NET [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to check if the input tbNRIC exist in the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strNric = tbNRIC.Text;
Session["nric"] = strNric;
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EADPRJConnectionString"].ConnectionString))
{
con.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select PNRIC from Patient", con);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
if (myReader[1].ToString() == tbNRIC.Text)
{
flag = true;
break;
}
}
if (flag == true)
Response.Write("<script>alert('Patient Profile Successfully Deleted');window.location ='ClientUpdate.aspx';</script>");
else
Response.Write("<script>alert('Patient Profile Unsuccessfully Updated');</script>");
}
}
}
I strongly suspect you try to read second column since you write myReader[1]. A reader indexing is zero-based. You might need to change it as myReader[0].
Also I prefer to use GetXXX methods of reader as a personal reference which I found it more readable.
if (myReader.GetString(0) == tbNRIC.Text)
Also use using statement to dispose your command and reader as you did for your connection.
You are accessing the second column with myReader[1] but you're selecting only one.
Use the Where-clause instead of reading all from the table. You could also use ExecuteScalar since you only want a single bool value:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EADPRJConnectionString"].ConnectionString))
{
string sql = #"SELECT CAST(CASE WHEN EXISTS(SELECT 1 FROM Patient
WHERE PNRIC = #PNRIC)
THEN 1 ELSE 0 END AS BIT)";
using (var myCommand = new SqlCommand(sql, con))
{
myCommand.Paramaters.Add("#PNRIC", SqlDbType.NVarChar).Value = tbNRIC.Text;
con.Open();
bool deleted = (bool)myCommand.ExecuteScalar();
// ...
}
}
It will be better if You check patient existance without load all records from DB.
Do somthing like this:
SqlCommand myCommand = new SqlCommand("select PNRIC from Patient where PNRIC = #PNRIC", con);
myCommand.Parameters.AddWithValue("#PNRIC", tbNRIC.Text);
and check if you can read any row.
It would be better if you apply the filter at Command Text. Something like :
var strsql = "select PNRIC from Patient where PNRIC='"+ tbNRIC.Text + "'";
SqlCommand myCommand = new SqlCommand(strsql , con);
....
var flag = false;
myReader = myCommand.ExecuteReader();
if(myReader .HasRows) flag = true;

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);

Having worry with code! I'm using C# and SQL Server 2008 [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
I want to write a client query (full name, age, telephone, image, etc) using the combobox (choosing a name) and automatically want the data to be displayed in the textbox. It works ok except the image and throws an error:
There is no row at position 0
My code:
//combobox load
private void cbmodificar_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MELVIN-PC\\SQLEXPRESS; Initial Catalog= World_Computers; Integrated Security=True;");
string query = "select * from agregar_cliente where Nombre='" + cbmodificar.Text + "'";
SqlCommand comando = new SqlCommand(query, conn);
conn.Open();
SqlDataReader leer = comando.ExecuteReader();
if (leer.Read() == true)
{
idclienteTextBox.Text = leer["idcliente"].ToString();
txtnombre.Text = leer["Nombre"].ToString();
txtapellido.Text = leer["Apellido"].ToString();
txtcedula.Text = leer["Cedula"].ToString();
txtedad.Text = leer["Edad"].ToString();
txttelefono.Text = leer["Teléfono"].ToString();
txtdireccion.Text = leer["Dirreción"].ToString();
txtcorreo.Text = leer["Correo"].ToString();
cbestado.Text = leer["Estado"].ToString();
cbsexo.Text = leer["Sexo"].ToString();
}
else
{
idclienteTextBox.Text="";
txtnombre.Text="";
txtapellido.Text="";
txtcedula.Text="";
txtedad.Text="";
txttelefono.Text="";
txtdireccion.Text="";
txtcorreo.Text="";
cbestado.Text="";
cbsexo.Text = "";
}
leer.Close();
DataSet ds = new DataSet("agregar_cliente");
SqlDataAdapter dp = new SqlDataAdapter(query,conn);
byte[] misdatos = new byte[0];
dp.Fill(ds, "agregar_cliente");
DataRow myrow = ds.Tables["agregar_cliente"].Rows[0]; //<<< i dont know//
misdatos = (byte[])myrow["Imagen"];
MemoryStream ms = new MemoryStream(misdatos);
imagenPictureBox.Image = Image.FromStream(ms);
}
You need to check if there is a row that you want to access,
if (ds.Tables["agregar_cliente"].Rows.Count > 0)
{
DataRow myrow = ds.Tables["agregar_cliente"].Rows[0];
......
}

Compare a list of objects to an object [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a button ADD CV. When a user logs on to the website, I check a table "cv" {id_member, id_cv}, if the id_member exists already in the table, the ADD CV button is disabled, otherwise the user can click it.
I retrieve all id_members from DB in a list (c) of classes (cv { int Id_candidat}). I need to check for the existence of logged user's id in this list (extracted from the Session variable).
This how I do it, but it's not working:
protected void Page_Load(object sender, EventArgs e)
{
List<cv> c = new List<cv>();
SqlConnection con = new SqlConnection(#"Data Source=p5-pc\sqlexpress;" +
"Initial Catalog=recrutement_online_3;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "select id_candidat from cv";
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cv p3 = new cv();
p3.Id_candidat = int.Parse(dr[0].ToString());
c.Add(p3);
}
dr.Close();
con.Close();
cv r = new cv();
r.Id_candidat = int.Parse(Session["Id_candidat"].ToString());
if (c.Contains(r))
{
Button1.Enabled = false;
}
...
My question is, How can I check for the existance of logged user's cv in database?
You can check for candidate existence when filling the list of available cvs:
...
bool candidatExists = false;
int idCandidat = int.Parse(Session["Id_candidat"].ToString());
while (dr.Read())
{
cv p3 = new cv();
p3.Id_candidat = int.Parse(dr[0].ToString());
c.Add(p3);
if(p3.Id_candidat == idCandidat)
{
candidatExists = true;
}
}
dr.Close();
con.Close();
Button1.Enabled = !candidatExists;
You can use linq Any to check for the existence of the candidate ID in the CV's list assuming that you've exposed a non private id member of your cv class (you haven't been clear):
bool showAddCvBtn = c.Any(id => id.id_member == r.Id_candidat);

Categories