I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.
Related
i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
This is my code and I'm new to C# and trying to learn, basically I have a project where specialists are being scheduled in their specialty using fullcalendar, but when I created the dropdownlist for specialty and then made a listbox for the specialist in each specialty being selected it keeps saying that there's an error on cmd.ExecuteScalar(); What am I doing wrong?
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT id, name, active, modifiedDate, note FROM sldb.dbo.Services", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(this.DropDownList1.SelectedItem.Value != "0")
{
String CS = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using(SqlCommand cmd = new SqlCommand("select firstName from sldb.dbo.Specilist where serviceID= #serviceID", con))
{
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#serviceID", this.DropDownList1.SelectedItem.Value);
con.Open();
object firstName = cmd.ExecuteScalar();
con.Close();
this.ListBox1.Text = firstName.ToString();
}
}
}
}
else
{
this.ListBox1.Text = "Please select name from list";
}
}```
If the error is on ExecuteScalar, there is something wrong with your query. I'm noticing Specialist is spelled wrong in the select statement. Try correcting that and let me know if that helps.
note that executeScalar return the first column of the first row in the dataset. Try wrap the executescalar in a try catch
try
{
object firstName = cmd.ExecuteScalar();
}
catch(Exception error)
{
//display error message error.Message;
}
Step through the code, I'd be tempted to put the value in a string to see what Scalar is returning.
string strPeek = cmd.ExecuteScalar().ToString();
Also, run the SQL separately to be sure the query is not erroneous.
I asked a question [HERE] and we got all the information stored in the database SQL Server CE database.
The question remains now how to get the information stored back into variables.
This line of code:
myReader.SqlCeReader();
will not compile, I am asked if I have missed a compiler reference what ever that is.
The information is stored as strings with an Integer “ID” primary key.
The information will be used to create shortcuts on a disk suitable for launching, images in paint, executable programs and so on. They should not be more than strings which is why I find it hard to do, it should be simple.
A sample record
id=int NstacksName=String NstacksPath=String.
I think I have it all wrong and am surprised it even compiles this far.
private void label2_Click(object sender, EventArgs e)
{
string DirName;
SqlCeConnection conn = new SqlCeConnection("Data Source=C:\\Users\\username\\Documents\\Visual Studio 2010\\Projects\\NStacks1\\NStacks1\\Database1.sdf");
String name;
try
{
conn.Open();
SqlCeCommand Command = new SqlCeCommand("SELECT * FROM NStacks1 WHERE ID = 1", conn);
DataTable Data = new DataTable();
SqlCeDataAdapter adapter = new SqlCeDataAdapter(Command);
SqlCeDataReader myReader;
try
{
myReader.SqlCeReader();
DirName = Data.ToString();
con.Close();
name = DirName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
private void button4_Click(object sender, EventArgs e)
{
string SName, NStackPath;
string source=("Data Source=C:\\Users\\username\\Documents\\Visual Studio 2010\\Projects\\NStacks1\\NStacks1\\Database1.sdf");
SqlCeConnection Con = new SqlCeConnection(source);
try{
Con.Open();
string Query= "SELECT * FROM Nstacks1 WHERE ID=1";
SqlCeCommand command = new SqlCeCommand(Query , Con);
SqlCeDataReader dr = command.ExecuteReader();
if (dr.Read())
{
textBox1.Text=(dr["NStacksName"].ToString());
label2.Text = (dr["NStacksItem"].ToString());
}
Con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
}
private void Delete_Click(object sender, EventArgs e)
{
//i have used this query for delete button
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter();
OleDbConnection con = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb");
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb";
con.Open();
//this is the query i have used
OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
con.Close();
}
//i have table named:car_model & attribute as Description
Your quotes don't look right, but my eyes are not great and anyway, the compiler would pick that up immediately, so I guess it's something else.
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = #Des", con);
comm.Parameters.AddWithValue("#Des", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
Also, use the '#' character to prevent SQL Injection issues. I don't think this is necessarily a problem with MS Access, but it's a good habit to get into.
https://www.w3schools.com/sql/sql_injection.asp
I have the database updating with the UserName of the person who uploaded a file and am trying to retrieve only the files the current user uploaded, to display in the gridview.
The page displays the current user name and when that person uploads a file everything is fine. Though when that user hits the search button, all records show up and I get the error:
Error:Invalid column name 'test'
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataReader reader;
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM UserUpload WHERE UserName = #un";
command.Parameters.Add(new SqlParameter("#un", UN));
command.Connection = conn;
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}
Change this line
string UserSearch = "SELECT * FROM UserUpload WHERE UserName =" + UN;
to
string UserSearch = string.Format("SELECT * FROM UserUpload WHERE UserName ='{0}'",UN);
you want to match to username as string strings are being wrapped in '' in SQL
If you would be matching by number it would work fine as numbers do not have this requirement.
UPDATE to UPDATE:
Change to something like this (untested)
SqlCommand com = new SqlCommand(UserSearch, conn);
{ DataSet ds = com.ExecuteReader();
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
conn.Close();
}
You would benefit from reading this
Use Parameters instead of assinging the Value to the query string
protected void ButtonSearch_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
try
{
string UN = Session["New"].ToString(); ;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string UserSearch = "SELECT * FROM UserUpload WHERE UserName = #un";
SqlCommand com = new SqlCommand(UserSearch, conn);
com.Parameters.Add(new SqlParameter("#un", UN));
com.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
LabelMessage.Text = ("Error:" + ex.Message);
}
}