Divyesh
Divyesh

Reputation: 438

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?

Upvotes: 0

Views: 741

Answers (4)

Pawan Nogariya
Pawan Nogariya

Reputation: 8960

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.

Upvotes: 1

Jeb's
Jeb's

Reputation: 406

private void bindGrid(DataTable dTable) { try {

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

Upvotes: 0

Divya
Divya

Reputation: 436

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.

Upvotes: 1

Hugo Yates
Hugo Yates

Reputation: 2111

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.

Upvotes: 0

Related Questions