0

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....

enter image description here

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?

4

1 回答 1

1

由于您将直接从数据库中提取到单独的控件中,因此您可以避免数据绑定并直接填充您的文本框。

例如,当您的用户设计的表单初始化时,您可以枚举所有TextBoxes

var textControls = Controls.OfType<TextBox>().ToList();

然后,当您实际执行SELECT语句时,您可以动态填充这些TextBox控件:

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++);
        }
    }
}

上述代码的好处在于,无论您在用户设计的表单上有多少字段或文本框,它对于您创建的每个表单都是相同的。

如果您需要将结果保存回您的数据库,您可以在表单关闭时执行类似的过程:枚举您的TextBoxes,构建查询字符串的参数,然后执行它。

同样,如果您想进行数据绑定,您可以创建一个List<>将 SQL 数据读入的字段(而不是直接将其读入您的TextBox控件)。然后,枚举TextBox控件并使用List<>.

于 2013-08-02T12:09:27.487 回答