Im working on a method to make all my SQL Querys and then databind them to Repeaters, DataLists And so on…
protected void sqlQuery(Control controlName, String query) {
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
cmd.Connection = conn;
try {
cmd.CommandText = query;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
controlName.DataSource = dt;
controlName.DataBind();
} catch (Exception error) {
Label1.Text = "Error!<br/>" + error;
}
}
Then i would call the method with my control name that i want to databind to.
Like:
sqlQuery(Repeater1, "SELECT * FROM someTable");
sqlQuery(DataList1, "SELECT * FROM someTable");
But that dosent work now since it dont know the control type when i just use Control..
So how would i do this?
The problem occurs because
Controldoes not have the properties/methods you require, and these properties are not defined on an interface or base control type.Therefore you have to use something called reflection, this allows you to the call properties and methods (as well as lots of other things) that you require without having any compile time knowledge of these, of course if you pass in a control without these you will get a nasty exception and there is a performance hit when using reflection – but in your case it would be trivial.
I dont have an IDE handy but something along these lines should do it.
}