Getting an object back from my GridView rows

前端 未结 4 1792
Happy的楠姐
Happy的楠姐 2021-02-08 10:34

Basically, i want my object back...

I have an Email object.

public class Email{
    public string emailAddress;
    public bool primary;
    public int c         


        
相关标签:
4条回答
  • 2021-02-08 11:21

    Well I ended up looping through my List EmailCollection, which was saved into the ViewState.

    So in the page, a Save button is clicked, when the event is caught, I loop through my List Collection and grab the row from the GridView by index.

    On the GridViewRow I have to use a GridView1.Rows[i].Cells[j].FindControl("myControl1") then get the appropriate value from it, be it a check box, text box, or drop down list.

    I do see that a GridViewRow object has a DataItem property, which contains my Email object, but it's only available during the RowBound phase.

    Unfortunately If/When i need to expand upon this Email Collection later, by adding or removing columns, it'll take a few steps.

    protected void SaveButton_OnClick(object sender, EventArgs e){
        for (int i = 0; i < this.EmailCollection.Count; i++)
        {
            Email email = this.EmailCollection[i];
            GridViewRow row = this.GridView1.Rows[i];
    
            string gv_emailAddress = ((TextBox)row.Cells[0].FindControl("EmailAddress")).Text;
            if (email.EmailAddress != gv_emailAddress)
            {
                email.EmailAddress = gv_emailAddress;
                email.Updated = true;
            }
            ...
        }
    }
    

    I'd still be open to more efficient solutions.

    0 讨论(0)
  • 2021-02-08 11:23

    If you want to hold onto an object like this its easiest to use the viewstate, although you will be duplicating the data but for a small object it should be ok.

    ViewState.Add("EmailObj", Email);
    
    EMail email = (Email)ViewState["EmailObj"];
    
    0 讨论(0)
  • 2021-02-08 11:26

    ASP.NET Databinding is a one-way operation in terms of object manipulation. However, the DataSource property will contain a reference to your EmailCollection throughout the response:

    EmailCollection col = (EmailCollection)this.GridView1.DataSource;
    

    But I have a feeling that what you really want is a control that manipulates your EmailCollection based on user input and retrieve it in the next request. Not even webforms can fake that kind of statefulness out of the box.

    0 讨论(0)
  • 2021-02-08 11:28

    Just a thought, basically a roll your own but not that tricky to do:

    Store the list that you use as a datasource in the viewstate or session, and have a hidden field in the gridview be the index or a key to the object that matches the row.

    In other words, each row in the gridview "knows" which email object in the list that it is based on.

    0 讨论(0)
提交回复
热议问题