I have an idea of what supposed to do just not exactly sure how to put it all together. I'm trying to search records in my data using a text box. I would like if the user didnt know the whole address just to be able to enter a portion of the address and still return records. If I enter the full address then a record returns. But if I just enter the first couple letters and search nothing returns.
Thanks
Here is what I have :
protected void btnFind_Click(object sender, EventArgs e)
{
string searchFor = txtFirstName.Text.Trim();
int results = 0;
string errorText = "No records found";
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Contacts.mdb");
conn.Open();
DataSet ds = new DataSet();
string cmd = "SELECT * FROM Contact WHERE Address LIKE '+searchFor ' ";
OleDbDataAdapter da = new OleDbDataAdapter(cmd, conn);
da.Fill(ds, "Search");
DataRow[] row;
DataRow dr;
row = ds.Tables["Search"].Select("Address='" + searchFor + "'");
results = row.Length;
if (results > 0)
{
dr = row[0];
txtFirstName.Text = dr["FirstName"].ToString();
txtLastName.Text = dr["LastName"].ToString();
txtEmail.Text = dr["Email"].ToString();
txtAddress.Text = dr["Address"].ToString();
txtPhone.Text = dr["Phone"].ToString();
}
else
{
lblError.Text = errorText;
}
conn.Close();
}
1. you are misusing single quotes in your query. you need to wrap up the string variables with single quotes.
2. you are not properly adding parameter in your query. you need to close parameter
with concatenation + operator
3. you need to use % for searching.
example : if you want to search in between you can use % before and after your search string
This
string cmd = "SELECT * FROM Contact WHERE Address LIKE '+searchFor ' ";
should be
string cmd = "SELECT * FROM Contact WHERE Address LIKE '%"+ searchFor +"%'";
You could try this code:
string cmd = "SELECT * FROM Contact WHERE Address LIKE '%"+ searchFor +"%'";
Related
This question already has an answer here:
how to i search if there is a same id in a database?
(1 answer)
Closed 6 years ago.
private void Add_Box_Click(object sender, EventArgs e)
{
string phoneNumber;
if (string.IsNullOrWhiteSpace(Id_Box.Text))// To check if the Id_box is empty or not
{
MessageBox.Show("Please Enter Your ID");// need to enter ID in order to save data
}
///////////////////////////////////////////check the Extension Box////////////////////////////////////////////////////////////////////////////////////
else
{
if (string.IsNullOrWhiteSpace(Ext_Box.Text))
{
phoneNumber = Phone_Box.Text;// if it is empty then it will only show the phone number
}
else
{
phoneNumber = Phone_Box.Text + "," + Ext_Box.Text; // show the phone number and the extension if there is something in the extension
}
///////////////////////////////////////////////////////////Save it to the Database///////////////////////////////////////////////////////
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Contact_List(Id, Name, Adress1, Adress2, City, Province, Postal_Code, Phone, Email)VALUES('" + Id_Box.Text + "','" + Name_Box.Text + "','" + Adress1_Box.Text + "','" + Adress2_Box.Text + "','" + City_Box.Text + "','" + Province_Box.Text + "','" + Code_Box.Text + "','" + phoneNumber + "','" + Email_Box.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Information Added", "Confirm");
/////////////////////////////////////Show new set of data after insert a new data/////////////////////////////////////////////////////////////
SqlCeCommand cmd2 = new SqlCeCommand("Select * from Contact_List;", con);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmd2;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
////////////////////////////////Empty The Box/////////////////////////////////////////////////////////////////////////////////////////////////
Id_Box.Text = String.Empty;
Name_Box.Text = String.Empty;
Adress1_Box.Text = String.Empty;
Adress2_Box.Text = String.Empty;
City_Box.Text = String.Empty;
Province_Box.Text = String.Empty;
Code_Box.Text = String.Empty;
Phone_Box.Text = String.Empty;
Ext_Box.Text = String.Empty;
Email_Box.Text = String.Empty;
}
}
This code will store Id, name, etc to the database. But when there is a same Id, i want to delete it. When i delete it both of the same Id will be deleted and i don't want that so is there anyway to check duplicate before it store it to the database?
I want to do something like this if possible :
if ( the values in id column == to the Id_textBox) {
MessageBox.Show("Duplicate ,PLease enter anotherId")
}
Possible?
Before executing your INSERT SQL statement, try running the SQL int ContactCount = (int)cmd.ExecuteScalar("SELECT COUNT(*) FROM CONTACT_LIST WHERE Id = '" + Id_Box.Text + "'")
If ContactCount > 0 then you can do the DELETE your suggesting.
Can I also recommend that you use a SQL UPDATE instead of DELETEing and INSERTing the same record.
Also, read-up on SQL Injection attacks. Building a SQL statement, like you're doing here, using the values input by a user leaves you exposed to that type of vulnerability.
First of all, like in all these answers: Don't use string concatenation but parametrized queries to prevent SQL-injection.
For your problem:
You can either do a
string query = "SELECT count(*) from ContactList Where id = #id";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = (int)cmd.ExecuteScalar();
if count > 0 the id already exists.
Or you can do a
string query "IF NOT EXISTS(SELECT count(*) from ContactList Where id = #id) INSERT INTO ContactList(Id, ...) VALUES(#id, ...)";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = cmd.ExecuteNonQuery();
count will then contain the number of rows affected, ie 0 if the value already existed, or 1 if it did not exist, but was newly inserted.
I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";
My code is producing an Incorrect syntax near '(' exception. I have tried two different ways but they both produce the same exception. I am trying to update a record in the database.
Here is my code and the line that produces the exception is the Execute non query line. The updater.Fill(dtable) which is commented out also produces the same exception.
protected void btnSave_Click(object sender, EventArgs e)
{
int found = 0; // No match found so far
// Get the current selected Manufacturer
string currentManufacturer = grdManufact.SelectedRow.Cells[1].Text;
string currentIsModerated = grdManufact.SelectedRow.Cells[3].Text;
// Connect to the database
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
// Try to find if new record would be a duplicate of an existing database record
if (txtManufactureName.Text != currentManufacturer)
{
string findrecord = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(findrecord, conn);
DataTable dt = new DataTable();
found = adpt.Fill(dt);
}
if (found == 0) // New record is not a duplicate you can proceed with record update
{
String query;
if (checkBoxModerated.Checked)
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','true') WHERE ManufacturerName = " + currentManufacturer + ";";
}
else
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','false') WHERE ManufacturerName = " + currentManufacturer + ";";
}
using (SqlCommand command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
//using (SqlDataAdapter updater = new SqlDataAdapter(command))
// {
// DataTable dtable = new DataTable();
// updater.Fill(dtable);
// }
txtMessage.Text = "Manufacturer record changed Successfully";
txtManufactureName.Text = "";
txtDescription.Text = "";
checkBoxModerated.Checked = false;
}
else
{ // Record is a duplicate of existing database records. Give error message.
txtMessage.Text = "Sorry, that manufacturer name already exists.";
}
}
You are using the incorrect syntax for UPDATE statements.
Instead of
UPDATE Table (Fields) VALUES (Values) WHERE ...
It should be
UPDATE Table SET Field1=Value1, Field2=Value2 WHERE ...
Additionally, you have a SQL injection vulnerability (although this is not the reason for your exception).
Do not use string concatenation for SQL queries with user input. Use prepared statements instead.
Try this approach , it's safer also:
var isModerated = checkBoxModerated.Checked ; //true or false
//var isModerated = (checkBoxModerated.Checked)? 'true' : 'false' ;
command.Text = "UPDATE VehicleManufacturer
SET ManufacturerName = #manufacturerName,
ManufacturerDescription = #manufacturerDescription,
IsModerated = #isModerated
WHERE ManufacturerName = #manufacturer_name";
command.Parameters.AddWithValue("#manufacturerName", txtManufactureName.Text);
command.Parameters.AddWithValue("#manufacturerDescription", txtDescription.Text);
command.Parameters.AddWithValue("#isModerated", isModerated);
command.Parameters.AddWithValue("#manufacturer_name", txtManufactureName.Text);
command.ExecuteNonQuery();
I need to get 6 values from database and bind them to link button texts her is the code
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string post = Request.QueryString["post"];
////string title = "nokia";
string date = DateTime.Now.ToShortDateString();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\nokiaoaq\Desktop\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
try
{
conn.Open();
//string str = "insert into Table1 (title , date_ ,www, cat) values (' " + TextBox1.Text + "','" + DateTime.Now.ToShortDateString() + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Text + "')";
////string str = "INSERT INTO Table1 (title,date_,www ) values ('ddddddd','aaaaaaa','qqqqqq')";
string str =
//"SELECT from table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee";
"SELECT table1.title FROM table1 WHERE cat = 1 and datee='" + date + "'ORDER BY datee DESC";
SqlCommand objcmd = new SqlCommand(str, conn);
SqlDataAdapter da1 = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
da1.Fill(dt);
//DataRow dr = new DataRow();
//DataRow dr = ds.Tables[0].Rows[0];
foreach (DataRow dr in dt.Rows)
{
ml1.Text = dr[0].ToString();
ml2.Text = dr[1].ToString();
ml3.Text = dr[2].ToString();
ml4.Text = dr[3].ToString();
ml5.Text = dr[4].ToString();
ml6.Text = dr[5].ToString();
}
}
catch (Exception ex)
{
Label4.Text = "Failed to connect to data source";
}
finally
{
conn.Close();
}
}
}
ml is link button id
You are trying to assign 6 fields from the row returned to 6 different textboxes, but your select query asks for just one field. If you want more than one field returned then add their names to the select query (change fieldX to the appropriate field name).
string str = "SELECT title, field1, field2, field3, field4, field5 " +
"FROM table1 WHERE cat = 1 and datee=#dt ORDER BY datee DESC";
also do not use string concatenation to build the sql statement. Use always a parametrized query
SqlCommand objcmd = new SqlCommand(str, conn);
objcmd.Parameters.AddWithValue("#dt", datee);
.....
this will avoid problem with formatting strings, date, numbers etc, but also the sql injection problem.
By the way, I hope that your code returns just one row because, as it stands now, if you have more than one row returned then only the one with the earliest date will be shown in the textboxes. (And if this is the case then the order by is useless). If you have more than one row returned then you should consider to bind the datatable to a GridView to show all records returned.
I have folowing code of c# in which I am making connection with access db and and using some conditions.I call a single row from db by using where clause in query.When I Logged into the page it gets data accurately.But after some time when i refresh the page it shows the folowing error
"There is No Row at position 0"
My code is is Bellow
protected void Page_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|OID.mdb;Persist Security Info=False;");
//OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Select * from EMAILS WHERE EMAIL= '" + GlobalData.Email + "'";
//cmd.CommandText = "Select * from EMAILS";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
String email = ds.Tables[0].Rows[0][1].ToString();
if (email == GlobalData.Email)
{
Label2.Text = GlobalData.Email;
Label1.Text = GlobalData.Name;
Label3.Text = GlobalData.LastName;
Label1.Visible = false;
Label3.Visible = false;
Label4.Text = Label1.Text + ' ' + Label3.Text;
}
}
I am querying data from DB and using where cluse with Global Variable to retrive a single row
Can Any one Please tell me that how can i Remove this issue or can i loop through the DB that evry time when user login it gets data using loop and then follow the condtion
That means your query is not returning anything and therefore when you call this line:
String email = ds.Tables[0].Rows[0][1].ToString();
You get an exception because there's no Row[0]
If you want to avoid that error do something like:
if (ds.Tables[0].Rows.Count>0)
{
String email = ds.Tables[0].Rows[0][1].ToString();
///...
}
Don't do select * ever in your code. Get used to list the exact columns you want to select from the table. For example:
select email_address from Emails where id= 5
Extra comment: Your query above is kind of pointless; it seems that you are trying to select an email address from a table using the same email address in the where clause. Why do you need to select it from the database if you already know the email? Judging by the variable name (GlobalData.Email) it seems that this is a predefined value...