Monday, 30 November 2015

How to bind gridview using entity framework from designer and backend code ?



Using Designer


Step 1:

Create gridview instance on the page where you want your gridview :

<asp:GridView ID="grdEducation" runat="server" ></asp:GridView>

Step 2:

Move to design page, you will get something like this :


Step 3:

Click on the arrow shown in the image, you will be provided with this form:




Here i have selected Entity and given it name "BindEducation", you can provide any,..
If you want the gridview to be bind with the help of sql then go for sql database and so on..


Step 4:

After that click "OK", now you will have this form :



Provide the name of the connection string which you have created at the time of entity creation and click next.

Step 5:



Select the table to which you need to bind and then select the columns required from that table.
Finally click "Finish". Now your gridview is binded with the required table.



Using Code :


Using code is also quite easy, below I have provided the way to bind the gridview/ repeater for a specific user from a table:

Designer

<asp:GridView ID="grdEducation" runat="server" AutoGenerateColumns="False"
><Columns>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%#Eval("emp_course") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Board/College">
<ItemTemplate>
<asp:Label ID="lblCollege" runat="server" Text='<%#Eval("emp_college") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year Passed">
<ItemTemplate>
<asp:Label ID="lblYear" runat="server" Text='<%#Eval("emp_yearPassed") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


code.cs



db_EmployeeManagEntities context = new db_EmployeeManagEntities();
protected void Page_Load(object sender, EventArgs e)
{
BindEducationGrid();
}

private void BindEducationGrid()
{
string empId = Session["ProfileEmpId"].ToString();
grdEducation.DataSource = (from emp in context.tbl_employeeEducation where emp.emp_Id == empId select emp).ToList();
grdEducation.DataBind();
}



No comments:

Post a Comment