textbox search like in google - c#

I am using C#.net Windows form , and I need to create a search textbox which will display combo box values (similar to google search); The values displayed in the combo box will be values from the SQL 2005 database (example the user is searching on FirstName, the combobox will display all firstnames, which get filtered as the user types in more letters.... if user is searching on LastName, the combo box displays all LastName values in the database.. etc)
when I am doing the above task
I have written the sql query like this
SELECT distinct(person_Firstname+''+person_Lastname)
AS
name FROM persondetails
WHERE name Like '%'+#name+'%'
when I am executing this query it gives error like this --- must declare a scalar varaible
my aim is when i am entering first letter in textbox it will display all names starting with that letter like in google...
can any one correct this ....
private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(#"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+#name+'%'";
con.Open();
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
tbautocomplete.AutoCompleteCustomSource = namecollection;

It sounds like you're trying to build an AutoComplete feature in your app. You're only missing the parameter on your SqlCommand. Try this:
string searchFor = "%" + txtName.Text + "%"; //the string the user entered.
cmd.CommandText = #"SELECT distinct(person_Firstname+''+person_Lastname) AS name
FROM persondetails
WHERE person_Lastname Like #name
OR person_Firstname LIKE #name";
cmd.Parameters.AddWithValue("#name", searchFor);
Your WHERE clause must use the column name in your table. It sounds as if you want to match either the first or last name columns with your search token.
WHERE person_Lastname LIKE #name
OR person_Firstname LIKE #name

The functionality you're looking for is called AutoComplete. I'm not familiar with an AutoComplete control in Windows forms, but if there isn't a built in one, there will certainly be third-party controls that do this.
The AutoComplete control will likely provide an event callback where you can put your SQL query to provide the possible completions.
As for your SQL error, it looks like it might be an issue with column names, but it is difficult to tell without your schema.
Edit:
I see you're using an AutoComplete contol already. The problem in your SQL is that your #name parameter is in your query, but you haven't added the parameter to the cmd object, so it doesn't know what value to put there.

Related

Issue while showing result of a query from database to DataGridView

working with an assignment here i am able to view all data from database to grid view but the data appears to be unsorted and it displays all data i only want to display the result of a query in the DataGridView the code i have tried is :
private void btnmeritbsit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dbpath);
string query = "select Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo order by I_Percentage desc";
con.Open();
dataGridView1.ColumnCount = sdr.FieldCount;
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dataGridView1.Rows.Add(sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
}
con.Close();
}
i was getting the whole values through datatable and dataAdapter but nothing works !!stuck!!
// DataTable dtbl = new DataTable();
// sda.Fill(dtbl);
// dataGridView1.DataSource = dtbl;
What I wrote in the other answer, in pictures. This is using a VB app, but it doesn't matter because the steps are the same and you're not actually going to be writing much more than one line of code
Right click project, add new dataset
Right click surface, add tableadapter
Add a connection string, Next. Name it, Next
Add a query that selects all from your table, WHERE (id column) = #id
Rename the methods to add "ByID". It will be obvious why later. Finish:
Right click table adapter, Add Query
Proceed through choosing "Select that returns rows" and entering a query that seeks users by last name:
Give good names to the new methods. Finish. Save:
Go to the forms designer, make sure Data Sources tool panel is showing (View Menu)
Drag the Users grid node from Data Sources onto the form
It has pre-made a textbox for the ID, because that's the first query in the tableadapter. We'll change it to lastname. Click the button, change its name, change the text it shows. Always make sure your control names are up to date and relevant.
You can see I changed the label too, and I also changed the name of the textbox (you can't see it) and I changed the name of everything in the tray under the designer, so it starts with underscore:
I do this because VB is case insensitive and calling variable the same name as their type is a bad idea in any language, and makes intellisense confusing in VB. You don't have to add the leading underscores in C#. It's enough to discriminate on case alone, though arguably not always wise:
Now we need to change the code. Double click the FillBy button. It goes to code. Maybe you have some code already, maybe not. Make sure the code fills the table using the relevant input. This is the only part of the process that really requires you to think about what you're doing and what your variables are called (they may be different to mine)
The code probably defaulted to saying
_usersTableAdapter.FillByID(_myDataSet.Users, new Guid(_lastNameToolStripTextBox.Text));
Because it used to be set up for you to type an id (guid or int, my db has a guid) in that box but we have changed it for lastname. So we need to change the FillByID (and now you see why we give them sensible names, not FillBy1 and FillBy2) so it's FillByLastName, and we need to change the code so we pass a string lastname, not a guid ID
_usersTableAdapter.FillByLastName(_myDataSet.Users, _lastNameToolStripTextBox.Text);
That's the only code you have to write. Remember I named my things on the form using leading underscores, so my code has leading underscores. If you dont rename your things, your code won't have leading underscores
Now run the app:
Look at all those John Smiths! They are different users, of course - the ID is different for every one. You can even write new details in here and press save to update the db..
From one line of code! :)
this works perfectly fine just after a few changes :)
private void btnmeritbscs_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=DESKTOP-UMA0VFO;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
string query = "select prgstatus,Applicant_no,A_Name,Father_Name,T_Matric,O_Matric,M_Percentage,T_Inter ,O_Inter ,I_Percentage from applicantinfo where prgstatus like 'bscs' order by I_Percentage desc";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
dataGridView1.ColumnCount = sdr.FieldCount;
while (sdr.Read())
{
dataGridView1.Rows.Add(sdr["prgstatus"], sdr["Applicant_no"], sdr["A_Name"], sdr["Father_Name"], sdr["T_Matric"], sdr["O_Matric"], sdr["M_Percentage"], sdr["T_Inter"], sdr["O_Inter"], sdr["I_Percentage"]);
}
con.Close();
}

How to populate database information from dropdown selection?

I have a students table, a courses table and a student/courses table to show the students enrolled in a course. The table is in SQL Server 2008 and the front end in C# and Asp.net.
In the student/courses table I would like to be able to have a dropdown menu that will allow me to select the student ID stored on the database and then populate the student's name, last name and middle initial in a textbox or label.
How can I possibly do this? Any examples? Thank you for your help!
You can use either ADO.net, if not familiar then
on page load event
SqlCommand cmd = new SqlCommand();
cmd.Connection= new Class1().getconnection();
cmd.CommandText = "SELECT * FROM Profile";
cmd.Connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr["YahooId"].ToString());
}
in "cmd.CommandText" instead of "Profile" use your table name, and under "while(dr.read()) use your column name instead of "YahooId"

How to use user input as parameter in SQL query in windows form application?

I want to attach a DataSet with parameterized query. Something like a user entering a value in a text box then hit submit button.
I have created a Text Field and a click button event something like :
private void Btn_GetProjDetails_Click(object sender, EventArgs e)
{
string userEnteredProjId = tab3ProjIdInput.Text;
}
but now don't know how to use this userEnteredProjId variable in my query?
I haven't tried the manually coding all the data-connections path. Instead added the GUI in VS2012 to add a data source. Then using this data source I have learned we can add datasets, and then use these DataSets to just drag and drop in our form. So I created a dataset and then dataset toolbox, I added my table and created a query but don't know how to use the userEnteredProjId in my query here.
You never want to just insert a value from a user into an SQL query because that is a huge SQL injection risk. It is better to use parameters, and better still if you do some validation on the parameters before using them. Here is a basic example of using a command parameter.
using (cmd command = new SqlCommand())
{
string sql = "Select * from table where projid=#UserEnteredProjid";
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("UserEnteredProjid", your_value_here);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//do something;
}
}
Well, your query is just a string variable I'm guessing, like "select * from table". You just want to take some user entered data to augment your query:
string query = "select * from table where projid = " + UserEnteredProjid;

exact command for storing in the oracle table

This is for a website in C#,Visual Studio 2010.
I've created a form with many textboxes, a date picker, dropdownlist, etc.
I've created a table in sqlplus with the columns with necessary types(varchar, number, date).
When I click the submit button in my form, I want to store the data in the table I've created.
Just to make it simpler for you guys, assume I have 3 text boxes
(name(text), id, date(i've printed the date in the text box as string)).
When I click submit it should fill the table with these data.
Im struggling to get the OracleCommand to execute this.
cmd = new OracleCommand(______, con);
If there is any other way I can do this by manipulating the types also its welcome :)
The insert syntax for oracle commands generally follows the pattern;
string query = #"INSERT INTO SOME_TABLE VALUES (SOME_COLUMN_1 = :SomeParam1,SOME_COLUMN_2 = :SomeParam2 )";
OracleCommand command = new OracleCommand(query, connection) { CommandType = CommandType.Text };
command.Parameters.Add(":SomeParam1", OracleDbType.Varchar2).Value = "Your Val 1";
command.Parameters.Add(":SomeParam2", OracleDbType.Varchar2).Value = "Your Val 2";
connection.ExecuteNonQuery();
See more reference examples here;
Using Named Parameters with Oracle ODP.NET

C# and SQL SELECT

Currently I am working on a project regarding C# and SQL and I have a problem regarding the SELECT function and I cannot find any solutions on-line.
The scenario is regard searching query from C# through SQL server and display the results in a Data Grid View at C#.
I'm using Visual Studio 2008 and SQL Server Studio 2008.
Before starting the project I just did a quick Windows form from Visual studio and just did a datagridview, 2 text boxes and a Search Button.
At SQL Server I have a a database with a table DVD and I want to search, from this Windows form with the DVD ID and Name.
I started with the DVD ID and implemented this code :
private void btnView_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
DataTable t = new DataTable();
string sqlString = "SELECT * From DVD where Id ='" + txtID.Text+ "'";
SqlDataAdapter dt = new SqlDataAdapter(sqlString, c);
dt.Fill(t);
dtgv1.DataSource = t;
}
and it worked :)
Then I changed the code to
string sqlString = "SELECT * From DVD where Name ='" + txtName.Text+ "'";
so that I can search with Name of the DVD but when I started the program and searched with the Name it just showed a blank database
Also is there any way that I can change the code so that I can either search with the ID or with the Name ?
Thanks for your help and time
Thoughts:
Make sure txtName.Text has a value
Try SQL select using Enterprise Manager, Toad, or some other query tool. What do you get?
Try using LIKE as example below
Worst case, maybe check the Collation for the Table, perhaps its set to 'Case Sensitive' text matching.
Both ID and Name:
SELECT * FROM DVD
WHERE Id=[ID Value]
OR Name LIKE '%[Name Value]%'
Or you could use SQLCommand with parameters like this:
SqlConnection c = new SqlConnection(#"Data Source=GILBERTB-PC\SQLEXPRESS;Initial Catalog=DVDandGameBooking;Integrated Security=True");
string queryString = "SELECT * From DVD where Id = #id";
var paramId = new SqlParameter("id", SqlDbType.VarChar);
var query = new SqlCommand(queryString, c);
query.Parameters.Add(paramId);
If you really want to use an SQLDataAdapter, you can set the select command to the one I wrote above. Otherwise, you can use a dataReader and iterate through the results.
Also, using parameters like this makes your query easier to read and makes it safer to SQL injections. It should always be considered.
Edit1: If you want to search with either the Id or the Name, you can just make 2 parameters, and put an OR between the 2, and maybe use the keyword like instead of = in your query. If the values can be null, you may want to build your query dynamically, depending on the values that are not null.

Categories

Resources