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

Dropdownlist based filtering in MVC 3 using EntityFrameWork(EDM) Modalfirst Method


SomeTimes We Need To Filter our items using dropdownlist we did it in asp.net let’s see how to do it in mvc using entity frame work Modalfirst method

To Implement Model First Method First We need to create the DataBase

Create Datatable as follows

And insert data in table as follows

Then create new project as follows

Open VisualStudio2010–> New Project –> asp.net mvc 3 web application

Then One popup window will come select in that as shown below

Then add images folder under content folder and add .EDMX file to our Project

Don’t know how to add ClickHere

Then add _layout.cshtml file for adding css

Then add controller first

The write following action and  code in this controller

MvcApplication2.Models.MySampleDBEntities db = new Models.MySampleDBEntities();
    public ActionResult SearchNames(string ddlcontent)
    {
        var list = new List<string>();
        var nameqry = from n in db.Images
                      select n.PlayerName;
        list.AddRange(nameqry.Distinct());
        ViewBag.ddlcontent = new SelectList(list);
        var names = from m in db.Images
                    select m;
        if (string.IsNullOrEmpty(ddlcontent))
            return View(names);
        else
            return View(names.Where(s => s.PlayerName.Contains(ddlcontent)));
    }

After completion of this add required view as follows

Right click on action in controller and select add view then click on ok.

Now u have added view, then write following code in that view

@model IEnumerable<MvcApplication2.Models.Image>
@{
ViewBag.Title = "SearchNames";
}

<h2>SearchNames</h2>
@using (@Html.BeginForm("SearchNames", "Names", FormMethod.Get))
{
@Html.DropDownList("ddlcontent", "All")<input type="submit" value="Filter" />;
}
<table border="4" style="border: medium dashed #FF0000">
<tr>
<th>
PlayerName
</th>
<th>
Play
</th>
<th>
CountryName
</th>
<th>
Image
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.PlayerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Play)
</td>
<td>
@Html.DisplayFor(modelItem => item.CountryName)
</td>
<td>
<img src="@item.ImagePath" height="100" width="100"/>
</td>
</tr>
}
</table>

After completion this give default routing details as ur controller name and action name

After completion of all these run ur application

u can get output as follows

DownloadSampleCode

How to call wcf service from wpf client


DataBaseDesign:

First create database with name MySampleDB and create table as follows with name UserDetails

then add data to table as follows:

WCFService Creation:

First go to file newproject–>wcfservicelibrary

Then add required service files as follows

1. interface class

2.Class Implementing InterFace

3.UserDefinedClasses(if any used)

Write following code in Userdefined Class:

Write this code in Interface Class:

Then Write Following Code in Class implementing Interface

After Completion of creating service run the application

now service will hosted check service is hosted of no as follows

After completion of service hosting you can get the following window

To check wether your service is running or not call the service methods in

wcftestclient window as follows

Now your service is Hosted successfully.

Now prepare client as follows

WPFClient:

Open new visualstudio go to file–> new Project–>wpfclient

Design wpfclient as follows

This is the code for above window design

  1. <Window x:Class="WpfClient.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4. Title="MainWindow" Height="500" Width="800">
  5.     <Grid>
  6.         <GroupBox Header="Details" Height="361" HorizontalAlignment="Left" Margin="500,27,0,0" Name="groupBox1" VerticalAlignment="Top" Width="266">
  7.             <Grid>
  8.                 <Label Content="EnterID:" Height="28" HorizontalAlignment="Left" Margin="16,17,0,0" Name="label1" VerticalAlignment="Top" FontWeight="Bold" FontSize="16" />
  9.                 <Label Content="UserID:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,122,0,0" Name="label2" VerticalAlignment="Top" />
  10.                 <Label Content="UserName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,162,0,0" Name="label3" VerticalAlignment="Top" />
  11.                 <Label Content="LastName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,204,0,0" Name="label4" VerticalAlignment="Top" />
  12.                 <Label Content="Location:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,244,0,0" Name="label5" VerticalAlignment="Top" />
  13.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="101,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
  14.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,167,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
  15.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,127,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
  16.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,209,0,0" Name="textBox4" VerticalAlignment="Top" Width="120" />
  17.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,249,0,0" Name="textBox5" VerticalAlignment="Top" Width="120" />
  18.                 <Button Content="GetSingleRecord" Height="36" HorizontalAlignment="Left" Margin="25,66,0,0" Name="button1" VerticalAlignment="Top" Width="196" Click="button1_Click_1" />
  19.             </Grid>
  20.         </GroupBox>
  21.         <GroupBox Header="AllDetails" Height="361" HorizontalAlignment="Left" Margin="22,27,0,0" Name="groupBox2" VerticalAlignment="Top" Width="453">
  22.             <Grid>
  23.                 <DataGrid AutoGenerateColumns="False" Height="263" HorizontalAlignment="Left" Margin="14,73,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="413" AlternatingRowBackground="#FFDEA5DE" RowBackground="#FFFFBEA5" FontSize="18" FontWeight="Bold">
  24.                     <DataGrid.Columns>
  25.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  26.                             <DataGridTemplateColumn.CellTemplate>
  27.                                 <DataTemplate>
  28.                                     <TextBlock Text="{Binding Path=UserId}"></TextBlock>
  29.                                 </DataTemplate>
  30.                             </DataGridTemplateColumn.CellTemplate>
  31.                         </DataGridTemplateColumn>
  32.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  33.                             <DataGridTemplateColumn.CellTemplate>
  34.                                 <DataTemplate>
  35.                                     <TextBlock Text="{Binding Path=UserName}"></TextBlock>
  36.                                 </DataTemplate>
  37.                             </DataGridTemplateColumn.CellTemplate>
  38.                         </DataGridTemplateColumn>
  39.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  40.                             <DataGridTemplateColumn.CellTemplate>
  41.                                 <DataTemplate>
  42.                                     <TextBlock Text="{Binding Path=LastName}"></TextBlock>
  43.                                 </DataTemplate>
  44.                             </DataGridTemplateColumn.CellTemplate>
  45.                         </DataGridTemplateColumn>
  46.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  47.                             <DataGridTemplateColumn.CellTemplate>
  48.                                 <DataTemplate>
  49.                                     <TextBlock Text="{Binding Path=Location}"></TextBlock>
  50.                                 </DataTemplate>
  51.                             </DataGridTemplateColumn.CellTemplate>
  52.                         </DataGridTemplateColumn>
  53.                     </DataGrid.Columns>
  54.                 </DataGrid>
  55.                 <Button Content="GetDataFromDataSet" Height="37" HorizontalAlignment="Left" Margin="14,22,0,0" Name="button2" VerticalAlignment="Top" Width="183" Click="button2_Click_1" />
  56.                 <Button Content="GetDataFromUserDefinedType" Height="39" HorizontalAlignment="Left" Margin="241,20,0,0" Name="button3" VerticalAlignment="Top" Width="186" Click="button3_Click_2" />
  57.             </Grid>
  58.         </GroupBox>
  59.     </Grid>
  60. </Window>

After Completion of designing we need to Create Proxy for service to consume service:

To create Proxy Do the following:

First Copy The Address Of  Service:

Then Add System.ServiceModel  dll file from .net tab of add reference

Then RightClick on your Project select Add ServiceReference:

After Adding this proxy if you want to see things added to servicereference

first select project the click on showhidden files as shown in below diagram

Then Write Following Code In CodeBehind:

Then Satart Calling From Client:

DownloadSampleCode

AJAX::Edit Update Delete Using Accordion Control Using EntityFrameWork


SomeTimes We need to use accordion only to edit update delete

for that, this is the code:

In .aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="btnShow" runat="server"
onclick="btnShow_Click" Text="Click here to see accordion" />
<div>
<cc1:Accordion ID="Accordion1" runat="server"
FadeTransitions="true" RequireOpenedPane="false"
HeaderCssClass="accordionHeader"
ContentCssClass="accordionContent" onitemcommand="Accordion1_ItemCommand">
<HeaderTemplate><%# Eval("Description") %>
</HeaderTemplate>
<ContentTemplate>
<asp:Image ID="btnImg" ImageUrl='<%#Eval("Image") %>'
runat="server" Height="100" />
<br />
<asp:Label id="lbl1" Text="Features :"
style="font-weight:bold; color:Blue" runat="server" />
<%# Eval("Feature") %>
<br />
<asp:Label id="lbl2" Text="Vendor:"
style="font-weight:bold; color:Blue" runat="server" />
<%# Eval("Seller") %>
<br />
<asp:Label id="lb3" Text="Price:"
style="font-weight:bold; color:Blue" runat="server" />
<%# Eval("Price") %>
<br />
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Edit">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandArgument='<%#Eval("Id") %>' CommandName="Delete">Delete</asp:LinkButton>
</ContentTemplate>
</cc1:Accordion>
<asp:Label ID="lblresult" runat="server"/>
<asp:Button ID="btnShowPopup" runat="server" style="display:none" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlpopup"
CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="209px" Width="400px" style="display:none">
<table width="100%" style="border:Solid 3px #D55500; width:100%; height:100%" cellpadding="0" cellspacing="0">
<tr style="background-color:#D55500">
<td colspan="2" style=" height:10%; color:White; font-weight:bold; font-size:larger" align="center"> Details</td>
</tr>
<tr>
<td>
<asp:Label ID="lblID" Font-Bold="true" ForeColor="Green" runat="server"></asp:Label>
</td>
</tr>
<tr><td>
<asp:Image ID="Image1" runat="server" Height="100" Width="100"/></td></tr>
<tr><td>
<asp:TextBox ID="tb2" runat="server" Text="Label"></asp:TextBox></td></tr>
<tr><td>
<asp:TextBox ID="tb3" runat="server" Text="Label"></asp:TextBox></td></tr>
<tr><td>
<asp:TextBox ID="tb4" runat="server" Text="Label"></asp:TextBox></td></tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="ButtonUpdate" runat="server" OnClick="Update" Text="Update"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>

CodeBehind:

 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    static int ItemNo;
    protected void btnShow_Click(object sender, EventArgs e)
    {
        DatabaseModel.DatabaseEntities obj = new DatabaseModel.DatabaseEntities();
        var x = (from n in obj.Items
                 select n);
        Accordion1.DataSource = x;
        Accordion1.DataBind();
    }
    protected void Accordion1_ItemCommand(object sender, CommandEventArgs e)
    {
        ItemNo = Convert.ToInt32(e.CommandArgument);
        DatabaseModel.DatabaseEntities obj = new DatabaseModel.DatabaseEntities();
        if (e.CommandName == "Edit")
        {
            Class1 cls = new Class1();
            var x = (from n in obj.Items
                     where n.Id == ItemNo
                     select new
                     {
                         n.Description,
                         n.Image,
                         n.Seller,
                         n.Price,
                         n.Feature
                     }).FirstOrDefault();
            this.ModalPopupExtender1.Show();
            lblID.Text = x.Description;
            Image1.ImageUrl = x.Image;
            tb2.Text = x.Feature;
            tb3.Text = x.Seller;
            tb4.Text = x.Price;
        }
        else if (e.CommandName == "Delete")
        {
            var x = (from n in obj.Items where n.Id == ItemNo select n).FirstOrDefault();
            obj.Items.DeleteObject(x);
            obj.SaveChanges();
            btnShow_Click(sender, e);
        }
    }
    public void Update(object sender, EventArgs e)
    {
        DatabaseModel.DatabaseEntities obj = new DatabaseModel.DatabaseEntities();
        var x = (from n in obj.Items where n.Id == ItemNo select n).FirstOrDefault();
        if (x != null)
        {
            x.Description = lblID.Text;
            x.Feature = tb2.Text;
            x.Seller = tb3.Text;
            x.Price = tb4.Text;
            obj.SaveChanges();
            btnShow_Click(sender, e);
        }
    }
}

DownLoad SampleCode

How to call a stored procedure using entity framework(edm)


First u need to create some database including tables and related stored procedures after completing this task we need to add that data base to our front end as entity framework for that we do some procedure. If u want that procedure please refer

https://chikkanti.wordpress.com/2012/02/08/how-to-add-entity-data-model/

When adding .edmx file we need to check tables and stored procedures as shown below

calling stored procedure using edm

after completion of .edmx file we need to add the available stored procedures in our .edmx to functions

for that first open modal browser and then open EntityContainer

then right clickon function imports and choose add function import as shown in below figure

We can get one window to select storedprocedure as follows

In that window we have different fields

1. function import name: this is the function name we will use in our front end to call stored procedure.

2. storedprocedurename: this is the storedprocedure name in our database and .edmx file we need to call

3. returns a collection of this will tell which type of output is coming from storedprocedure(we need to select this).

If we want to call that imported function

First create object for edm like

SRMModel.SRMBEntities ent = new SRMModel.SRMBEntities();

And call function like

ent.ForgotPWD();//if it don’t have any parameters to pass

if it have any input parameters call as follows

ent.ForgotPWD(UName, Qsn, Ans);

How to retrieve data from database using EntityFrameWork


Create database tables as follows:

First add ADO.NET entity data modal to our project

Display data using grid view:

Form Design:

Add new form and place a GridView in form.

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>

Code Behind:

Write following code in pageload event:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetData();
    }
}
public void GetData()
{
    //first create object to the EDMEntities as follows…
    sampledatabaseModel.sampledatabaseEntities obj = new sampledatabaseModel.sampledatabaseEntities();
    //retrive data using edm…
    var x = (from n in obj.emps select n);
    //bind data to gridview
    GridView1.DataSource = x;
    GridView1.DataBind();
}

======================================================

How to get data from database based on some parameter using EntityFrameWork

Form Design:

1.Keep one gridview  to display data

2.One textbox to enter parameter

3.One button to send value

4.One literal to display error message

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
<br />
Enter EmpNo:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>

Code behind:

In form load write above code only

Then write following code in button click event

if (TextBox1.Text.Trim() != string.Empty)
{
int i = int.Parse(TextBox1.Text);
var x = (from n in obj.emps
where n.eno == i
select n);
if (x != null)
{
GridView1.DataSource = x;
GridView1.DataBind();
}
else
{
Literal1.Text = "Enter Proper Empid from above details";
GetData();
}
}
else
Literal1.Text = "textbox should not be empty";

How to add Entity Data Model


Creating a new web site:

The first step is to create a new Web application:

  1. In Visual Studio, select FileNewWebsite from the main menu.
  2. Choose the choose empty website installed template. Click OK. The solution is created.

Adding an Entity Data Model

You will now add an Entity Data Model to your solution.In the Solution Explorer, right-click your application and select Add,New Item…. From Visual Studio installed templates select ADO.NET Entity Data Model. Click Next.

 You will now see the Entity Data Model Wizard. You will use the wizard to generate the Entity Data Model from the world example database. Select the icon Generate from database. Click Next.

You can now add the connection details to use which data connection should your application use to connect to the database. For this you can click on new connection, you will get one wizard like…

After adding the connection you need to choose which database objects do you want to include in your modal

Now you can get .edmx file as follows…