run SQL query

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a C# web app were i want to run a SQL query based on the selection
from the drop down. I have 4 selections on the drop down and I can pass 3 of
them fine due to they are in the database. I have one selection that is "Show
All" which i want to show everything in the database in my grid.

I have this as my dynamic query:
OdbcCommand ProjectListCmd = new OdbcCommand("select * from news where
Group='" + NewsGroup+ "'", database);

if the user selects show all then i want it like this.
OdbcCommand ProjectListCmd = new OdbcCommand("select * from news, database);

How can i get this to work? I had a
if (NewsGroup == "Show All")
{
OdbcCommand ProjectListCmd = new OdbcCommand("select * from news,
database);
}else{
dynamic query}

but i kept getting errors for my datalist not defined data adapter not
defined, which they are
 
Well, you haven't shown us quite enough code but:

OdbcCommand projectListCmd = null;
if (NewsGrou == "Show All"){
projectListCmd = new OdbCommand("SELECT * FROM News, database")
}else{
projectListCmd = new OldbCommand("SELECT * FROM news Where Group =
@NewsGroup", database);
projectListCmd.Parameters.Add("@NewsGroup",OdbcType.VarChar, 50).Value =
NewsGroup;
}
OdbcDataAdapter da = new OdbcDataAdapter(projectListCmd);
DataTable dt = new DataTable();
try{
//open connection
da.Fill(dt);
}finally{
projectListCmd.Dispose();
da.Dispose();
connection.Dispose();
}

grid.DataSource = dt;
grid.DataBind();


notice also how I switched your embedded and very dangerious SQL with a far
safer parameterized one..

Karl
 
firstly, is NewsGroup a string?
if it's a listbox it should be NewsGroup.SelectedItem.Text ==


why not something like:

OdbcCommand projectListCmd = new OdbcCommand ();

if ( NewsGroup == "Show All" )
{
projectListCmd.CommandText = "select * from news, database";
}
else
{
projectListCmd.CommandText = "select * from news where Group='" +
NewsGroup+ "'", database";
}

// etc...
 
NewsGroup is a string and a variable for the drop down selection since I'm
using it more then once.

What you have I tried in my code and I got an error for my data adapter
varaible, and my datalist variable, etc.
 
Back
Top