简体   繁体   中英

GridView.DataBind() difficulty

I am trying to fill a gridview like this:

 private void BindGridView(DataTable dTable)
 {
     gridView.DataSource = dTable;
     gridView.DataBind();
 }

In the same .cs file, I am using only gridView.DataBind(); , and it works. I want to know how the DataBind() method refers to the data source?

The place where you are calling only DataBind method actually not making any difference since the grid view already had DataSource and when you call this function it again bind it with the available data source

When you call this line even once in the page

gridView.DataSource = dTable;

It assigns datasource to the grid view and any subsequent call to DataBind method will bind the grid with the same already loaded data.

DataBind() method is used to bind Source to the server Controls.

DataBind() method forces gridview to bind with a particular DataSource. Since you have already referred your DataSource, and when you are using only DataBind(), it will take the previous DataSource by default, since it is there in the memory.

However, most controls perform bindings automatically. Thus, you don't need to use this method explicitly.

I hope, this is what you wanted to know.

DataBind is only rendering your datasource that's already been loaded into the object. You can do other binding's in aspx, for example <span><%#MyClass.RenderSomething()%></span> but nothing happens unless you instruct it to bind (ie page.DataBind(); in your cs).

You can define your DataSource in one section of your code and bind it in another is because your defining the source to the control (your GridView) and when DataBind is finally called is when that all gets processed into the output and event's such RowCreated get fired.

private void bindGrid(DataTable dTable) { try {

            gvSmokingStatus.DataSource = dTable;
            gvSmokingStatus.DataBind();            
    }
    catch (Exception ex)
    {
        throw ex;`enter code here`
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM