How to check if input exist in the database. ASP.NET [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 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;

Related

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

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

Why is my entered data not stored in Database? [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 8 years ago.
Improve this question
public List<TextBox> _textBoxes = new List<TextBox>();
protected void btmSubmit_Click1(object sender, EventArgs e)
{
dbDataItem();
}
public void dbDataItem()
{
dc.cnn.Open();
_textBoxes = getTextBox();
//foreach (TextBox text in _textBoxes)
//{
// _textBoxes.Add(text.Text.Trim());
// //StoreValue(text.Text);
//}
foreach (TextBox textBox in _textBoxes)
{
//TextBox txt = new TextBox();
//txt.ID = Panel2.FindControl("textBox").ToString();
string value = textBox.Text;
string query = "select name from DataItem where name = '" + value + "'";
SqlCommand cmd = new SqlCommand(query, dc.cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
int count = dt.Rows.Count;
if (count == 0)
{
int i = MaxCode1();
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
dc.cnn.Close();
}
else
{
Response.Write("<script language='javascript'>alert('This DataItem already exist in database');</script>");
}
}
dc.cnn.Close();
}
You don't run cmd2.
After setting Parameters, run it like this :
cm2.ExecuteNonQuery();
So, your code looks like this :
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
cmd2.ExecuteNonQuery();
dc.cnn.Close();
Calling SqlDataAdapter.Fill to execute an INSERT command is not correct. The Fill method is used to retrieve record from the database using a SELECT statement. In your code the INSERT statement is passed as the SelectCommand of the adapter and it is executed when you call Fill so the record is added to your database table. But there is no return value in your DataTable code object because the SelectCommand used by the Fill method has no SELECT statement assigned to it.
You need to split the two actions, first ExecuteNonQuery on the INSERT statement, then create the adapter with the correct SELECT statement
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
cmd2.ExecuteNonQuery()
SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM DataItem");
DataTable dt2 = new DataTable();
da2.Fill(dt2);

How to load a dropdown list box from Mysql database using C# asp.net? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to load the dropdown list box with a column of a table from Mysql in asp.net with C#.
So right now you've noted that you just want to load a single field. That's what the following code would do. It will select a single field, from a single table, and bind it to the combo box.
using (MySqlConnection c = new MySqlConnection(connString))
{
c.Open();
var sql = "SELECT field_name FROM table_name";
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
comboBox.ValueMember = "field_name";
comboBox.DisplayMember = "field_name";
comboBox.DataSource = dt;
}
}
However, I think the more general use of it might be something like this:
using (MySqlConnection c = new MySqlConnection(connString))
{
c.Open();
var sql = "SELECT key_field, display_field FROM table_name";
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
comboBox.ValueMember = "key_field";
comboBox.DisplayMember = "display_field";
comboBox.DataSource = dt;
}
}
Here you're listing data and have both a key_field and a display_field. The importance of that is generally combo boxes are used for lookup type data. Either way, when you wanted to get the value of the combo box, use the SelectedValue member.
comboBox.SelectedValue
Welcome to the Stackoverflow:)
Please refer below code snippet for your requiremrnt:
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id FROM Customers";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the combobox's items
while (reader.Read())
{
CustomerIdComboBox.Items.Add(reader.GetString("Id"));
}
}
}
}
string str="Select km from tablename;
SqlDataAdapter ad = new SqlDataAdapter(str,connection object);
DataSet ds = new DataSet();
ad.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
Textbox1.Text = ds.Tables[0].Rows[0][0].ToString();
}

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