What is the inverse DataBind () function in ASP.NET.

I am currently doing data binding to a grid view with a data source from an ArrayList. Is there a way to change the binding and get the value from the grid view with a single line code?

// Bind to GUI
ArrayList dsList;
gvName.DataSource = dsList;
gvName.DataBind();

// Current Way of getting code from GUI
int iRow = 0;
foreach (GridViewRow gvr in gvName.Rows)
{
    TextBox txtD1 = gvName.FindControl("textboxName") as TextBox;
    if (txtD1 != null) 
    {
        dsList[iRow].D1 = txtD1.Text;
    }
    ....
    iRow++;
}

      

Is there a way to make it shorter as one liner? Does the API have this?

gvName.ReverseDataBind();

      

+2


source to share


2 answers


There is no such method in the API.

If you are interested in getting the source of the binding when building the page, the best way to do this is to make the original class property on the page itself available in any of the page's methods. For example:



public class MyPage: Page {
    ArrayList dsList = new ArrayList();

    ArrayList DsList {
        get {
            return this.dsList;
        }
}

      

If you are interested in getting the binding source for postbacks (in response to client generated events), this is possible with some qualifications. Assuming you don't want to rebuild the binding source (for example, by re-querying the database, which should always be considered), you'll have to save it somewhere when you first get it in order to access it later. (Managing the data in a database doesn't do it yourself.) It might be a database somewhere, but sometimes for convenience, people save it before ViewState

or save it to Session

. Both of these approaches have their own risks, although they should be used with caution. ViewState

increases the size of HTML sent to the client, but Session

consumes server memory until it is explicitly cleared or the session ends.

+3


source


Well, the real answer is to use BindingList<T>

instead of an array, as this deals with all the two-way relationships between list and anchor, so you don't have to manually update the list from the grid.

However, if you cannot use BindingList<T>

, the best thing you can do is extract the data item from the string:



// Bind to GUI
ArrayList dsList;
dgvName.DataSource = dsList;
dgvName.DataBind();

// Slightly simpler way of getting code from GUI
int iRow = 0;
foreach (DataGridViewRow dgvr in gvName.Rows)
{    
    object item = dgvr.DataBoundItem;        
    dsList[iRow].D1 = item.ToString();

    iRow++;
}

      

The return value of the DataBoundItem can be assigned to the appropriate type for processing, which is somewhat easier than finding a text box control.

-1


source







All Articles