Crouch
Crouch

Reputation: 896

Select if string is like a field in database

I have a form where the user types in a name and it selects everything based on that name, Ideally i'd like to be able to have it so it would select everything from the database if they typed half of the name in or just a character so everyone whose first name is dave etc.

try
{
    this.access_PermissionTableAdapter.FillBy(
        this.vehicleManagementDataSet.Access_Permission,   
        this.userNameToolStripTextBox.Text);
}
catch (System.Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
}

This will select all fields when the name is spelt letter for letter but not if it is partially typed. I've been looking at the methods C# provides like contains and starswith but neither seem suitable.

Is there a way of selecting where the name is like what is typed in?

Upvotes: 0

Views: 162

Answers (4)

dvjanm
dvjanm

Reputation: 2381

If you want to use something like the SQL's LIKE operator on c# strings then use the Contains method.

For example you have a list of strings:

List<string> myStringList = new List<string>();
//fill the list

If you want to achieve the result of Amirreza Keshavarz's or P5Coder's answer not using a database then use Linq To Objects and Contains method.

IEnumerable<string> result = myStringList.Where(ms => ms.Contains("typed string"));

If you want the strings that just starts with the typed string then use this:

IEnumerable<string> result = myStringList.Where(ms => ms.StartsWith("typed string"));

Upvotes: 0

Rob Lyndon
Rob Lyndon

Reputation: 12671

If you have a strongly typed dataset, you can create your own custom queries (in your case, I'd call the query StartingWith, the SQL code of which is given by the other two responses, and it will generate a method called FillByStartingWith). See http://msdn.microsoft.com/en-us/library/kda44dwy(v=vs.80).aspx for instructions on how to do this.

Upvotes: 2

Ganesh Jadhav
Ganesh Jadhav

Reputation: 2848

Try this:

SELECT * FROM tbl_yourtable t WHERE t.columnname LIKE '%' + @searchstring + '%'

Upvotes: 1

Amir Keshavarz
Amir Keshavarz

Reputation: 3108

Try this:

 SELECT *
    FROM TABLE1
    WHERE COL1 LIKE '%TYPED NAME%'

Upvotes: 1

Related Questions