How to bind Dropdownlist in gridview using EntityFramework(EDM)


First Take new web site and add .edmx file

if you don’t know how to add .edmx file Clickhere

then add new webform and place a gridview as follows

then write this code in codebehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = from n in en.UserDetails select n;
            GridView1.DataBind();
        }
    }
    MySampleDBModel.MySampleDBEntities en = new MySampleDBModel.MySampleDBEntities();
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var x = from n in en.UserDetails
                    select new { n.UserId, n.UserName };
            DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
            ddl.DataTextField = "UserName";
            ddl.DataValueField = "UserId";
            ddl.DataSource = x;
            ddl.DataBind();
        }
    }
}

Output:
Advertisements

One thought on “How to bind Dropdownlist in gridview using EntityFramework(EDM)

  1. Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web
    Imports System.Web.UI

    Imports System.Web.UI.WebControls
    Imports System.Data

    Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
    GridView1.DataSource = From n In en.UserDetails n
    GridView1.DataBind()
    End If
    End Sub
    Private en As New MySampleDBModel.MySampleDBEntities()
    Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
    Dim x = From n In en.UserDetailsNew From { _
    n.UserId, _
    n.UserName _
    }
    Dim ddl As DropDownList = DirectCast(e.Row.FindControl(“DropDownList1”), DropDownList)
    ddl.DataTextField = “UserName”
    ddl.DataValueField = “UserId”
    ddl.DataSource = x
    ddl.DataBind()
    End If
    End Sub
    End Class

    i got error this line…..
    Private en As New MySampleDBModel.MySampleDBEntities()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s