简体   繁体   中英

Dynamically using SQL statements for SQLDataSource

I may or may not have a pretty simple question here for you guys. Basing my if-else statements off of the existence of a string, I am trying to either call a SELECT statement with a parameter or not and pass them both to the same resulting GridView.

Here is what I am trying to do:

 string query;
 if(BadgeNumLabel.Text != "")
 {
     query = "SELECT * FROM AUDITS";
 else
 {
     query = "SELECT * FROM AUDITS WHERE BADGENUM = :BadgeNumLabel";
     GridDataSource.SelectParameters.Add(new Parameter("BadgeNumLabel",TypeCode.String, BadgeNumLabel.Text));
 }

 GridDataSource.SelectCommand = query;
 GridView1.DataBind();

My .aspx code looks like this:

 <asp:SqlDataSource ID="GridDataSource" runat="server"
            ConnectionString="<%$ ConnectionStrings:OracleConnectionString %>" 
            ProviderName="<%$ ConnectionStrings:OracleConnectionString.ProviderName %>"  
            onselecting="GridDataSource_Selecting">


        </asp:SqlDataSource>  

Is there something I am missing? I am so stumped. I think it has to do something with passing the parameter BadgeNumLabel around but I'm not sure.

Any help is greatly appreciated! Thanks!

You need to assign the result of the GridDataSource to the GridView1.DataSource

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand GridDataSource= new SqlCommand();

GridDataSource.CommandText = "SELECT * FROM AUDITS";
GridDataSource.CommandType = CommandType.Text;
GridDataSource.Connection = sqlConnection1;

sqlConnection1.Open();

GridView1.DataSource = GridDataSource.ExecuteReader();
GridView1.DataBind();

EDIT

It's not literally ExecuteCommand, what I try to say is that you need to assign the result of the SqlCommand to the GridView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM