How to change TableAdapter CommandText at runtime

S

SWheaties

I have a GridView, which is bound to an ObjectDataSource. The
ObjectDataSource.TypeName points to a TableAdapter, and the
SelectMethod points to one of the methods. My goal is to be able to
change the SQL statement at runtime so I don't have to write a
bazillion queries to handle all the parameters I need to pass. So,
after much searching and experimenting I was finally able to kludge my
way through to extend the TableAdapter to allow me to set a SQL command
at runtime.

Both SetSQL and SetSQL2 in the following code appear to work - the
problem now is that they work one time only. I believe the issue is
related to my setting the DataSourceID - If I don't don't set it
to null, it crashes at runtime, complaining that both DataSourceID and
DataSource cannot be set.

Thanks for any help!


Here is the code:

//----------------------------------------------------------------
// This extends the tableadapter class

namespace DataSet1TableAdapters
{
public partial class ProductsTableAdapter
{

public void SetSQL2(DataSet1TableAdapters.ProductsTableAdapter
t, string SQLCmd)
{
t.CommandCollection[0].CommandText = SQLCmd;
}

public int SetSQL(DataSet1.ProductsDataTable t, string SQLCmd)
{
this.Adapter.SelectCommand = new
System.Data.OleDb.OleDbCommand(SQLCmd, this.Connection);

if (this.ClearBeforeFill)
t.Clear();

return this.Adapter.Fill(t);

}
}
}

//----------------------------------------------------------------
// The following is called when a when the form (GridView) is loaded

// use this if calling SetSQL
DataSet1.ProductsDataTable t = new DataSet1.ProductsDataTable();
DataSet1TableAdapters.ProductsTableAdapter p = new
DataSet1TableAdapters.ProductsTableAdapter();
p.SetSQL(t,basequery);
GridView1.DataSourceID = null;
GridView1.DataSource = t;



// OR use this if calling SetSQL2
/*
DataSet1TableAdapters.ProductsTableAdapter p = new
DataSet1TableAdapters.ProductsTableAdapter();
p.SetSQL2(p, basequery);
GridView1.DataSourceID = null;
GridView1.DataSource = p.GetProducts();
*/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top