Click to See Complete Forum and Search --> : Dynamic SQL


howardnl
March 6th, 2003, 10:36 AM
Hello,

I hope this isn't a dumb question, but from my limited experience I haven't been able to figure this out. I want to setup a generic function that takes a sql statement (could be any sql statement - dynamically built) as a parameter, opens a connection, etc, and populates a datagrid (I think a datagrid is what I want). Basically I just want to see the results of the query that I passed in.

Would a datagrid be best for this? I don't need (or want) to update or delete data in the database through the datagrid - I just want to see the results of the query.

Any thoughts? Thanks for your help.

Regards,
Nick

GMV
March 6th, 2003, 11:40 AM
Hi! try this!
Any questions?

// C#
private static void FillDataTable(String sqlProc, DataTable dataTable, SqlParameter[] Parameters)
{
SqlConnection connection = new SqlConnection(CONNECTION_STRING);
SqlCommand command = new SqlCommand(sqlProc, connection);
command.CommandType = CommandType.StoredProcedure;

foreach (SqlParameter par in Parameters)
{
command.Parameters.Add(par);
}
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}

public static void GetDataFromSomeStoreProc(DataTable datatable, SqlParameter[] Parameters)
{
FillDataTable("GetDataFromSomeStrProc", datatable, Parameters);
}

private void SomeCall()
{
int param1 = 1111;
string param2 = "ppp";
GetDataFromSomeStoreProc(yourDataTable,
new SqlParameter[] { new SqlParameter("@Param1", param1),
new SqlParameter("@Param2", param2)
});
}

howardnl
March 6th, 2003, 11:56 AM
Thanks GMV. I'll give it a shot!

pareshgh
March 6th, 2003, 12:00 PM
for filling the datagrid use
following code,

SqlDataAdapter dataAdapter=null;
DataSet _dataSet = null;

try
{
// Connection object
SqlConnection connection = new SqlConnection(connString);
// Create data adapter object
dataAdapter = new SqlDataAdapter(sqlString, connection);


// Create a dataset object and fill with data using data adapter's Fill method
_dataSet = new DataSet();
dataAdapter.Fill(_dataSet, "orders");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Problem with DB access-\n\n connection: "
+ connString + "\r\n\r\n query: " + sqlString
+ "\r\n\r\n\r\n" + ex.ToString());
this.Close();
return;
}