Reputation: 5866
I have created a Form Designer application. You can see the screentshot below. The user can design a screen and save it with a name. When the user saves a form, the application just saves the control's type(textbox,label,button...), name, width,height,location x, location y and etc....
Now, I want to let user save a SQL SELECT STATEMENT into the application, then let user bind the datatable from that SQL SELECT STATEMENT to the controls created by the user.
lets say, user has saved this SELECT statement like below
SELECT ID,NAME, LASTNAME FROM PERSONS
and form created by user has 3 textboxes. How can I bind those to each other?
Can you guys give me any clue?
Upvotes: 0
Views: 980
Reputation: 6026
Since you're pulling straight from the database into individual controls, you may be able to avoid data binding and just populate your text boxes directly.
For instance, when your user-designed form initializes you could enumerate all the TextBoxes
:
var textControls = Controls.OfType<TextBox>().ToList();
Then, when you actually execute your SELECT
statement you could dynamically populate those TextBox
controls:
using (var conn = new SqlConnection())
{
conn.Open();
var command = new SqlCommand(selectStatement, conn);
using (var rdr = command.ExecuteReader())
{
rdr.Read();
int i = 0;
while (i < rdr.FieldCount)
{
textControls[i].Text = rdr.GetString(i++);
}
}
}
The nice thing about the above code is that it is identical for every form you create no matter how many fields or textboxes you have on your user-designed forms.
If you need to save the results back to your database, you could do a similar process when the form closes: enumerate your TextBoxes
, build the parameters for the query string, and then execute it.
Similarly if you wanted to databind you could create a List<>
of fields that would read the SQL data into (instead of reading it into your TextBox
control directly). Then, enumerate the TextBox
controls and setup data bindings with the corresponding field in the List<>
.
Upvotes: 1