Hi, I'm a bit stumped as to how to do this.
I have a string[] with a list of users, and I want to query my database to select only the users in this array and bind the datasource to a GridView, but I don't know how to write an SQL query to search for multiple results from the same field.
E.g. Say I have two results in my string[], fred and bob.
How can I select data from the database for just those two users - "SELECT * FROM tblUsers WHERE UserName='bob' AND ??";
IF this is possible, I also need to bind it to a gridview. I tried the following, but it didn't work as I needed it to:
for(int a = 0; a < userArray.Length; a++)
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE UserName='" + userArray[a] + "'", conn);
SqlDataReader reader = command.ExecuteReader();
grid.DataSource = reader;
grid.DataBind();
conn.Close()
}
That 'worked', but as I'm sure you can see, the data that was bound to the gridview was only the last result found, not the whole result set.
Any help is greatly appreciated.
schuminator:
for(int a = 0; a < userArray.Length; a++)
{
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE UserName='" + userArray[a] + "'", conn);
SqlDataReader reader = command.ExecuteReader();
grid.DataSource = reader;
grid.DataBind();
conn.Close()
}
try out as below
String strUsers = String.Empty;for (int a = 0; a < userArray.Length; a++) strUsers = strUsers + @."'" + userArray[a] + @."',"; strUsers = strUsers.Substring(0, strUsers.Length - 1); conn.Open(); SqlCommand command =new SqlCommand("SELECT * FROM tblUsers WHERE UserName in (" + strUsers +")", conn); SqlDataReader reader = command.ExecuteReader(); grid.DataSource = reader; grid.DataBind(); conn.Close();
Good Luck./.
|||Sorry, I tried to delete the thread but it was too late.
I got it sorted...it was so simple, I feel like an idiot!
"SELECT * FROM tblUsers WHERE UserName='fred' OR UserName='bob'" etc
I also wrote a little for loop to add another OR... to the end of the string when necessary.
|||you can use above method also...
so instead of UserName='fred' OR UserName='bob'"......
if will formulate query using IN keywork as..
UserName in ('fred','bob')
|||ahh ok awesome, thanks :)
No comments:
Post a Comment