开发者

Populate controls auto-magically from an Entity Framework Context query

开发者 https://www.devze.com 2023-02-04 11:27 出处:网络
I have the following code: IList<AccountMember> query; using (DBEntities context = new DBEntities())

I have the following code:

IList<AccountMember> query;

using (DBEntities context = new DBEntities())
{

    Guid ModifyUser = new Guid(Session["ModifyUser"].ToS开发者_如何学Pythontring());

    query = (from AccountMember member in context.AccountMember
         where member.AccountMemberId == ModifyUser
         select member).ToList();


    foreach (AccountMember member in query)
    {
    //this.FirstName.Text = member.FirstName;
    ControlCollection controls = this.Controls;

    foreach (Control control in controls)
    {
        if (control is TextBox)
        {
        TextBox x = (TextBox)control;
        x.Text = member.FirstName; // want to replace the .FirstName with the TextBox ID value somehow
        }
    } // foreach (Control control in controls)
    } // foreach (AccountMember member in query)

} // using (DBEntities context = new DBEntities())

At the line containing x.Text = member.FirstName; I would like to replace the FirstName item with the TextBox ID string. So that I can just loop and populate my TextBoxes automatically


Have you tried creating a bindingsource then binding your text boxes to this.

At runtime you can then bind your EF entity to the binding source and your controls will be autopopulated.

A nice example can be found here - it shows binding to a grid, but the principle is similar for binding to individual controls.

Additionally to pull a single entity you can do:

AccountMember member = context.AccountMember
                              .Single(m => m.AccountMemberId == ModifyUser);

// Bind the fetched entity to the bindingsource and hence to the UI controls
// At runtime this is all that is needed to update the controls, as long as 
// you have set things up at design time.
myBindingSource.DataSource = member;
0

精彩评论

暂无评论...
验证码 换一张
取 消