Reputation: 429
I am currently in the process of transferring an Access97 Database Application to a new WinForms application.
We have a central form for all "Accounts" which shows the general account data, within that form there is a button that opens another form, the application gets the form name from a SQL query using an example of the table below.
| ClientID | FormName |
+----------+----------+
| 1 | frm1 |
| 2 | frm2 |
So if the ClientID is 1 then the button should open Form1 if the ClientID is 2 the button should open Form2.
My question is how would I get WinForms to run the query on the button click to then open the corresponding form found within the table?
Any help is much appreciated.
Upvotes: 0
Views: 1056
Reputation: 23831
You will need to write an SQL helper method. Something like the following (which I have not checked and hacked up)
public static T SQLGet<T>(SqlConnection conn, string sql)
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = conn;
command.CommandTimeout = 0; // No timeout - set or remove.
command.CommandText = sql;
return (T)Convert.ChangeType(Command.ExecuteScalar(), typeof(T));
}
}
you can use this like
SqlConnection conn = new SqlConnection(someValidConnectionString);
string formName = Utilities.SQLGet<string>(conn,
"SELECT [FormName] " +
"FROM [SomeTable] WHERE [ClientID] = 1;") // Not considering SQL injection here!
Now you can use reflection with the retrieved name formName
Type t = assembly.GetType(formName);
Form frm1 = (Form)Activator.CreateInstance(t);
I hope this helps.
Note. this does not have error handling.
Upvotes: 2