Compare a list of objects to an object [closed] - c#

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

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

Get One Column's Data from Db and Set it to multiple Checkboxes in C# [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 2 months ago.
Improve this question
I have multiple Checkboxes in a page and their values are being stored in one column. Now I want that if I get data from Db then Checkbox is checked if their value is store in that column.
What Store Procedure and C# code I use for this?
Here is my code;
private void SetRoles()
{
SqlCommand cmd2 = new SqlCommand("SPD_GetAllUsersList");
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#id", "ABC01");
SqlDataAdapter sda2 = new SqlDataAdapter();
cmd2.Connection = con;
sda2.SelectCommand = cmd;
DataTable dt2 = new DataTable();
sda2.Fill(dt2);
con.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
bool recfound2 = dr2.Read();
if (recfound2)
{
if (dt2.Columns[0].ToString() == "Add Staff".ToString())
{
CBAddStaff.Checked = true;
}
else
{
CBAddStaff.Checked = false;
}
if (dt2.Columns[0].ToString() == "Update Staff".ToString())
{
CBAUpdateStaff.Checked = true;
}
else
{
CBAUpdateStaff.Checked = false;
}
}
con.Close();
}
There are many things wrong with your peace of code my friend
Your code for reading data from database is too long, and doesn't even make much sense. Try this:
A little tip: read the data in a separate method.
private DataTable ReadRoles()
{
var cmd = new SqlCommand("SPD_GetAllUsersList");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", "ABC01");
var con = new SqlConnection("YourConnectionString");
var sda = new SqlDataAdapter(cmd, con);
var cmb = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
return ds.Tables[0];
}
Now we store the returned DataTable in a variable, and search through that:
var Roles = ReadRoles();
CBAddStaff.Checked = false;
CBAUpdateStaff.Checked = false;
foreach (DataRow row in Roles)
{
if (row["RoleId"].ToString() == "Add Staff") CBAddStaff.Checked = true;
else if (row["RoleId"].ToString() == "Update Staff") CBAUpdateStaff.Checked = true;
else continue;
}
Now, if you really need to use all of this in one method, I suggest you create method that does everything in the second piece of code I wrote: Call the ReadRoles(), uncheck both ckechboxes (so you don't need if-else , if-else), and set Checked of the right checkbox to true
Don't forget to vote and accept if you find this helpful

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;

I want to make a BioMetric Attendence System in C# ASP.net [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 don't Have any Idea about FingerPrint Scanner. Anyone know about how to save fingerPrint into database and match the fingerPrints in C# Asp.net. I'm using DigitalPersona and Microsoft Visual Studio 2010.
Do you give me some code snippets for this?
I shall be very thankful to you...
Regards
Zargham Nazeer Malik
You are using digital persona. after installing , a folder will be saved in c directory. Please check , code is present in that folder.It could already register and verify fingerprints
Below code is to save in database....
private void SaveButton_Click(object sender, EventArgs e)
{
MemoryStream fingerprintData = new MemoryStream();
Template.Serialize(fingerprintData);
fingerprintData.Position = 0;
BinaryReader br = new BinaryReader(fingerprintData);
Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length);
//Insert the file into database
SqlConnection cn = new SqlConnection("Data Source=10.115.5.3; Initial Catalog=EnrollmentSampledb;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("INSERT INTO tblUser VALUES(#ID_NUMBER, #FIRSTNAME, #LASTNAME, #FINGERPRINT, #DATE_ADDED, #DATE_MODIFIED)", cn);
cmd.Parameters.Add("ID_NUMBER", SqlDbType.NVarChar).Value = tboxIdNum.Text;
cmd.Parameters.Add("FIRSTNAME", SqlDbType.NVarChar).Value = tboxFname.Text;
cmd.Parameters.Add("LASTNAME", SqlDbType.NVarChar).Value = tboxLname.Text;
cmd.Parameters.Add("FINGERPRINT", SqlDbType.Image).Value = bytes;
cmd.Parameters.Add("DATE_ADDED", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("DATE_MODIFIED", SqlDbType.DateTime).Value = DateTime.Now;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
tboxIdNum.Text = "";
tboxFname.Text = "";
tboxLname.Text = "";
}

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];
......
}

Categories