Category Archives: EntityDataSource

EntityDataSource

[RESOLVED]Entity DataSource in .NET 4.5

I am looking in to the Application Compatability of .NET 4.5.I am looking for ASP.NET breaking changes.

http://msdn.microsoft.com/en-us/library/hh367887.aspx

 I want to understand what is that mean.

I am able to see the data getting populated without explictly calling DataBind in Page.LoadComplete event.

Can some one help in identifying the different between .NET 4.0 and 4.5 for this control.

 

System.Web.UI.WebControls.EntityDataSource control

The Page.LoadComplete event no longer causes the
System.Web.UI.WebControls.EntityDataSource control to invoke data binding for changes to create/update/delete parameters.

This change eliminates an extraneous trip to the database, prevents the values of controls from being reset, and produces behavior that is consistent with other data controls, such as
SqlDataSource and
ObjectDataSource. This change produces different behavior in the unlikely event that applications rely on invoking data binding in the
Page.LoadComplete event.

 

 

 

Hi vijayarul,

Thanks for posting!

As we know,Page.LoadComplete event will raise after control events.

This is described in MSDN:

“Raised at the end of the event-handling stage.

Use this event for tasks that require that all other controls on the page be loaded.

”, actually, we usually do some setting about page control.

About WebFrom lifecycle, you can refer to this link:

http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx

About your doubt, the MSDN have clearly described:

“The
Page.LoadComplete
event no longer causes the
System.Web.UI.WebControls.EntityDataSource
control to invoke data binding for changes to create/update/delete parameters.”

It says that we may set the create/update/delete parameters of
EntityDataSource
control in
Page.LoadComplete
event , if we do it in NET4.0, after
Page.LoadComplete
event,  the
EntityDataSource
control will once again retrieve data from db,  but in NET4.5, we will retrieve data from the control cache and send the data into the control like GridView control, the change eliminates an extraneous trip to the database.

If you still have any problem, please let me know.

Thanks!

[RESOLVED]X Value Member in my chart should be shown as a date

The X Value Member in my chart should be shown as a date, but the chart shows the x axis as 5 digit numbers, like  41287 and 41367. The table has the correct date values, but the chart is showing numbers. How do I format the x values to be date format?

<asp:Chart
ID="Chart1"
runat="server" DataSourceID="EntityDataSourceEstimateRequest">

<Titles><asp:Title
Text="Estimate
Request"

/></Titles>

<Series>

  <asp:Series
Name="Series1"
ChartType="Line"
XValueMember="ERDate"

  YValueMembers="EstimateRequestValue">

  </asp:Series>

</Series>

<ChartAreas>

<asp:ChartArea
Name="ChartArea1">

  </asp:ChartArea>

  </ChartAreas>

 </asp:Chart>

You can use this to format data XValueMember as follows:

<asp:Chart ID="Chart1" runat="server" DataSourceID="EntityDataSourceEstimateRequest">

<Titles><asp:Title Text="Estimate Request" /></Titles>

<Series>

  <asp:Series Name="Series1" ChartType="Line" XValueMember="ERDate"

  YValueMembers="EstimateRequestValue">

  </asp:Series>

</Series>

<ChartAreas>

<asp:ChartArea Name="ChartArea1">
     <AxisX>
         <LabelStyle Format="dd-MM-yyyy"/>
     </AxisX>
  </asp:ChartArea>
  </ChartAreas>
 </asp:Chart>

Hope this will help you!!Smile

[RESOLVED]GridView in Nested User Control with Ajax.

I was having the same query…but now its partially solved…
i am using Nested User Controls….
Like: I have a ‘A’ Usercontrol that contains the grid view
      then a ‘B’ User Control that contains ‘A’ n one more user control
      then a ‘C’ user Control that Contains ‘B’ and 2 more ajax control…
      i want row command in the ‘C’ user control

On rowcommand click a modal popup control should be visible.

How can i achieve this….

Hi,

I am sorry I am a little confused about your purpose. Assuming that you want to open a ModalPopupExtender when you click the Gridview, you can put the ModalPopupExtender in the TemplateField of the Gridview directly as follows:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="EntityDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnSelect" runat="server"
ImageUrl="~/Images/addtocart.gif"
ImageAlign="AbsMiddle" OnClick="btnSelect_Click" />
<ajax:ModalPopupExtender ID="gv_ModalPopupExtender" runat="server"
TargetControlID="btnSelect"
PopupControlID="pnlModalPanel"
CancelControlID="btnCancel"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID" HeaderText="ID"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="ProductPrice" HeaderText="ProductPrice"
SortExpression="ProductPrice" DataFormatString="{0:C}" />
</Columns>
</asp:GridView>

Then show as follows:

http://blog.dreamlabsolutions.com/post/2008/11/11/ModalPopupExtender-in-a-GridView-sample.aspx

If I have anything misunderstood, please let me know.

Best wishes,

insert not working from footer row in gridview (using EntityDataSource)

I have a GridView using an EntityDataSource that includes Edit/Delete buttons for all the data rows, and Insert/Cancel buttons in the footer.  Edit and Delete are working perfectly with no code behind.  Cancel seems to work as well (just clearing the footer
textboxes).  But no luck with Insert, it just seems to clear the footer textboxes with no errors and no inserted data.

I started to write my own in the code-behind using onRowCommand, but just as I verified that my code was getting called I discovered that Edit and Delete stopped working.  Would love to get this wired up without having to fill up the code behind.  Any help
much appreciated.

Here’s the key parts of the gridView and the EntityDataSource:

<asp:GridView ID="gvClasses" runat="server" AllowSorting="True" AutoGenerateColumns="False"

        DataKeyNames="id" DataSourceID="dsClasses" ShowFooter="true" >
    <Columns>
      <asp:TemplateField ShowHeader="False">
        <ItemTemplate>
          <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
          <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
          // asp:Labels displaying data
          
        </ItemTemplate>
        <EditItemTemplate>
          <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
          <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
          // asp:TextBoxes allowing edit
          
        </EditItemTemplate>
        <FooterTemplate>
           <asp:LinkButton ID="LinkButton4" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert"></asp:LinkButton>
           <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
          // asp:TextBoxes allowing edit
          
        </FooterTemplate>
        </asp:TemplateField>
      </Columns>
</asp:GridView>
<asp:EntityDataSource ID="dsClasses" runat="server" ContextTypeName="StudentTracker.dbEntities"
     EnableFlattening="False" EnableDelete="True" EnableInsert="True" EnableUpdate="True"
     EntitySetName="Classes">
</asp:EntityDataSource>

Please, follow the below link from MSDN , it may solve your problem,

http://msdn.microsoft.com/en-us/library/cc668211(v=vs.100).aspx

and an example from stack-overflow

http://stackoverflow.com/questions/3413485/how-do-i-insert-data-using-the-entitydatasource-control

Thanks

Thanks for the help and links!  As I searched and wrestled I kept noticing suggestions to use ListView instead of GridView for the insert. Finally decided to try it out, got edit, update, delete, and insert (in the footer) all running cleanly the first time
I tried it, without a single line in the code behind.

Never could get the GridView running without having to write it in the code behind. 

Great links and help though, thank you very much!

[RESOLVED]Conditional Cell Formating of GridView not happening in asp.net

I have been stuck with an issue that seems really simple, but I have no clue what is going wrong. I am a newbie with Asp and am therefore not aware of the debugging fundamentals.

I am trying to change the color of a cell text based on its value in the Result Column. I have attached the code for your reference. Kindly tell me whats wrong, nothign is getting reflected.

Columns> <asp:BoundField DataField="TestCaseID" HeaderText="TestCaseID" SortExpression="TestCaseID" /> 
<asp:BoundField DataField="Iteration" HeaderText="Iteration" SortExpression="Iteration" />
 <asp:BoundField DataField="StartTime" HeaderText="StartTime" SortExpression="StartTime" />
<asp:BoundField DataField="EndTime" HeaderText="EndTime" SortExpression="EndTime" /> 
<asp:BoundField DataField="Result" HeaderText="Result" SortExpression="Result" />
<asp:BoundField DataField="Comments" HeaderText="Comments" SortExpression="Comments" />
</Columns>
 <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>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=Test_Manager_DatabaseEntities"
 DefaultContainerName="Test_Manager_DatabaseEntities" EnableFlattening="False" EntitySetName="TestExecutionDetails"
Where="it.[TestExecutionID] = @ExecutionID ">
<WhereParameters> <asp:QueryStringParameter Name="ExecutionID" QueryStringField="ExecutionID" Type="Int32" />
 </WhereParameters> </asp:EntityDataSource>
<asp:QueryExtender ID="ctlMyQueryExtender" runat="server" TargetControlID="EntityDataSource1">
 <asp:SearchExpression DataFields="Result" SearchType="StartsWith"> <asp:ControlParameter ControlID="TextBoxName" />
</asp:SearchExpression>
 </asp:QueryExtender>
</ContentTemplate>
</asp:UpdatePanel>

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

 namespace ABCD
 {

public partial class TestExecutionResults : System.Web.UI.Page

 {

private int TestExecID;
protected void Page_Load(object sender, EventArgs e)

{

//Response.Cache.SetCacheability(HttpCacheability.NoCache);

//Response.CacheControl = "no-cache";

if (!Page.IsPostBack)

 using (Test_Manager_DatabaseEntities entities = new Test_Manager_DatabaseEntities())
{
Console.WriteLine(Request.QueryString["ExecutionID"]);
 TestExecID = Convert.ToInt32(Request.QueryString["ExecutionID"]);
}

}

 protected void Timer2_Tick(object sender, EventArgs e)
{
GridView1.DataBind();

 }

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{

if (e.Row.Cells[4].Text == "Pass")
{
e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
 }

else if (e.Row.Cells[4].Text == "Fail")

{ e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
 }
}
}
}
}

I assume you’ve hooked up the RowDataBound event properly since I can’t see your gridview line.

Otherwise put a breakpoint in the rowdatabound event and step through your code. The Cell index might be wrong or the cell content might not be macthing Pass/Fail.

Thank you MetalAsp.Net, I tried putting a breakpoint, it looks like the if condition is failing

if (e.Row.RowType == DataControlRowType.DataRow), because it does not continue into this conditional, instead it goes back to calling the function. Has it got something to do with the Timer.

Please help.

Thanks

Your code looks good, try this

if (e.Row.Cells[4].Text.Trim().ToLower() == "pass")
{
   e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
}
else
{
   e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
}

Thanks a lot oned_gk. You solved it. :)

Selected value in dropdownmenu not being retrieved when using OnItemUpdating in FormViewUpdate

I have two dropdownmenus that are dependent on each other. When a user selects a value form the top dropdownmenu it causes a postback and calls a method to update the second dropdownmenu, that works. Once the user saves the changes I am calling OnItemUpdating
to retrieve the new values in the drop down menus. I am able to retrieve and save the new value in the first drop down menu, but the value on the second dropdownmenu is not being saved. Why is the selected value not being retrieved?

Design Code

<asp:DropDownList ID="TruckTypeDDL" runat="server" SelectedValue='<%# Eval("FireTruckId") %>' DataSourceID="TruckTypeEDS" DataTextField="Name" DataValueField="Id" OnSelectedIndexChanged="TruckTypeDDL_SelectedIndexChanged" AutoPostBack="true" >
</asp:DropDownList>
 <asp:EntityDataSource ID="TruckTypeEDS" runat="server" ConnectionString="name=ModelContainer" DefaultContainerName="ModelContainer" EnableFlattening="False" OrderBy="it.[Name]" EntitySetName="FireTrucks" ContextTypeName="Model.ModelContainer">
</asp:EntityDataSource>

<asp:Label ID="modelID_lbl" runat="server" Visible="false" Text='<%# Eval("ModelId") %>'></asp:Label>
<asp:DropDownList ID="ModelTypeDDL" runat="server" DataTextField="Name" DataValueField="Id" >
</asp:DropDownList>

Code behind

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            string tType = Convert.ToString(Session["SelectedTruck"]);
            updateModels();
        }
    }

    protected void TruckTypeDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        var truckSelected = TruckTypeDDL.SelectedValue.ToString();
        Session["SelectedTruck"] = truckSelected;
    }

    protected void updateModels()
    {
        var ses = Session["SelectedTruck"];
        int iSelected = Convert.ToInt32(ses);
        var content = new ModelContainer();
        var modelTypes = from c in content.Models
                            where c.FireTruckId == iSelected
                            orderby c.Name
                            select new
                            {
                                Name = c.Name,
                                Id = c.Id
                            };
        var showModels = modelTypes.ToList();
        DropDownList Tmodels = (DropDownList)OrderFormView.FindControl("ModelTypeDDL");
        Tmodels.DataSource = showModels;
        Tmodels.DataBind();

    }


protected void OrderFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e) { DropDownList trucktype = (DropDownList)OrderFormView.FindControl("TruckTypeDDL"); var selectedTruckType = trucktype.SelectedItem.Text; var selectedTruckTypeID = trucktype.SelectedItem.Value; int iTruckTypeID = Convert.ToInt32(selectedTruckTypeID); e.NewValues["TruckType"] = selectedTruckType; e.NewValues["FireTruckId"] = selectedTruckTypeID; DropDownList modeltype = (DropDownList)OrderFormView.FindControl("ModelTypeDDL"); var selectedModel = modeltype.SelectedItem.Text; var selectedModelID = modeltype.SelectedItem.Value; int iTruckModelID = Convert.ToInt32(selectedModelID); e.NewValues["ModelType"] = selectedModel; e.NewValues["ModelId"] = selectedModelID; }

Thanks in advance

Hi bdassow,

According to your code and description, I think your problem may be caused by that  you have put the updateModel() into the if(IsPostBack).

So please try to change your code to the following:

if (!IsPostBack)
        {
           
        }
protected void TruckTypeDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        var truckSelected = TruckTypeDDL.SelectedValue.ToString();
        Session["SelectedTruck"] = truckSelected;
updateModel();
    }

If there have anything unclear, please let me know.

Best Regards,
Terry Guo

Terry,

I tried your suggestion, but it didn’t solve the problem yet.

It is strange when I select a different drop down item in the updateModel list the "selected" value in the html does not change.  It display correctly, but the html is not being updated properly. Have you ever seen this happen?

Thanks

bdassow

[RESOLVED]sorting elements in an EntityDataSource's navigation collection

I have a listView bound to the following (partial) EF datasource:

<asp:EntityDataSource ID="edsStudent" runat="server" Include="Parent,Days,Classes" ……

And a nested listView that displays the included/navigation-property "Days" as follows:

<asp:ListView ID="lvDays" runat="server" DataSource=’<%# Bind("Days") %>’ …….

Is there a way to control how that (nested collection? sub collection? navigation collection?) is sorted?

Thanks for any help-

Ugly, but working:

<asp:ListView ID="lvDays" runat="server" DataSource=’<%# Bind("Days") %>’ OnDataBinding="lvDays_DataBinding"…..

protected void lvDays_DataBinding(object sender, EventArgs e) {
    EntityCollection<Day> ds = (EntityCollection<Day>) lvDays.DataSource;
    lvDays.DataSource = ds.OrderBy(d => d.date);
}

[RESOLVED]sorting elements in an EntityDataSource's navigation collection

I have a listView bound to the following (partial) EF datasource:

<asp:EntityDataSource ID="edsStudent" runat="server" Include="Parent,Days,Classes" ……

And a nested listView that displays the included/navigation-property "Days" as follows:

<asp:ListView ID="lvDays" runat="server" DataSource=’<%# Bind("Days") %>’ …….

Is there a way to control how that (nested collection? sub collection? navigation collection?) is sorted?

Thanks for any help-

Ugly, but working:

<asp:ListView ID="lvDays" runat="server" DataSource=’<%# Bind("Days") %>’ OnDataBinding="lvDays_DataBinding"…..

protected void lvDays_DataBinding(object sender, EventArgs e) {
    EntityCollection<Day> ds = (EntityCollection<Day>) lvDays.DataSource;
    lvDays.DataSource = ds.OrderBy(d => d.date);
}

crud operations on junction table with entity data source?

I’m looking for a way to display a junction table in a (gridView/listView/whatever) to support CRUD operations on the rows in the junction table.  I have an app with two of them, both of which have been abstracted into navigation properties.  Ideally, I’d
like the grid to show fields from the related tables instead of just the FK’s in the junction table, but FK’s would be sufficient.  But I can’t find the table when I configure the data source….

Thanks for any help!

Hi ottenm,

Based on your description, my understand is that you would like to achieving the interaction of two GridViews.

If so, please try to refer to the following code:

The database:

create database Demo;
create table Merchant(ID int primary key, name varchar(20))
insert into Merchant values(101,'apple');
insert into Merchant values(102,'banane');

create table Contacts(ID int foreign key references Merchant(ID), price varchar(20))
insert into Contacts values(101,'33$');
insert into Contacts values(101,'43$');
insert into Contacts values(101,'53$');

In the aspx:

<form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridViewMerchant" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridViewMerchant_SelectedIndexChanged" >
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DemoConnectionString %>" DeleteCommand="DELETE FROM [Merchant] WHERE [ID] = @ID" InsertCommand="INSERT INTO [Merchant] ([ID], [name]) VALUES (@ID, @name)" SelectCommand="SELECT * FROM [Merchant]" UpdateCommand="UPDATE [Merchant] SET [name] = @name WHERE [ID] = @ID">
            <DeleteParameters>
                <asp:Parameter Name="ID" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="ID" Type="Int32" />
                <asp:Parameter Name="name" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="ID" Type="Int32" />
            </UpdateParameters>
        </asp:SqlDataSource>
        <asp:GridView ID="GridViewContacts" runat="server"></asp:GridView>
    </div>
    </form>

In the .cs:

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

        }

        protected void GridViewMerchant_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewMerchant.SelectedRow.ForeColor = Color.Red;
            string ss = GridViewMerchant.SelectedDataKey.Value.ToString();
            SqlConnection con = new SqlConnection("Data Source=(localdb)\Projects;Initial Catalog=Demo;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
            con.Open();
            SqlCommand cmd=new SqlCommand("select *from Contacts where ID=@ss",con);
            cmd.Parameters.Add(new SqlParameter("@ss",ss));
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds=new DataSet();
            da.Fill(ds);
            GridViewContacts.DataSource=ds;
            GridViewContacts.DataBind();
      }
}

Hope it can help you.

Best Regards,
Terry Guo

Thanks for your example Terry, but not what I’m looking for.  Working with only one grid, where the table only has foreign keys in it (see DB below).  The PK tables are already up and running, but I need to add CRUD ops to the FK table called ‘Junction’. 

CREATE TABLE [Merchants] (
	id INT PRIMARY KEY NOT NULL,
	name NVARCHAR(100) NULL
);

CREATE TABLE [Products] (
	id INT PRIMARY KEY NOT NULL,
	description NVARCHAR(100) NULL
);

CREATE TABLE [Junction] (
	mid INT NOT NULL, /* MerchantID FK */
	pid INT NOT NULL /* ProductID FK */
);

INSERT INTO [Merchants] (id, name) VALUES (1, 'm1');
INSERT INTO [Merchants] (id, name) VALUES (2, 'm2');
INSERT INTO [Products] (id, description) VALUES (101, 'apples');
INSERT INTO [Products] (id, description) VALUES (102, 'bananas');
INSERT INTO [Junction] (mid, pid) VALUES (1,101);
INSERT INTO [Junction] (mid, pid) VALUES (1,102);
INSERT INTO [Junction] (mid, pid) VALUES (2,102);

Hi ottenm,

From my understanding, you would like to operation the Junction table, and in GridView display the name and description which relate to Merchants and Products.

If so, please try to refer to the following solution:

In the sql file:

CREATE TABLE [Merchants] (
       id INT PRIMARY KEY NOT NULL,
       name NVARCHAR(100) NULL
);

CREATE TABLE [Products] (
       id INT PRIMARY KEY NOT NULL,
       description NVARCHAR(100) NULL
);
drop table [Junction]
CREATE TABLE [dbo].[Junction] (
    [mid] INT NOT NULL,
    [pid] INT NOT NULL,
    [jid] INT NOT NULL IDENTITY,
    CONSTRAINT [PK_Junction] PRIMARY KEY ([jid])
);

INSERT INTO [Merchants] (id, name) VALUES (1, 'm1');
INSERT INTO [Merchants] (id, name) VALUES (2, 'm2');
INSERT INTO [Products] (id, description) VALUES (101, 'apples');
INSERT INTO [Products] (id, description) VALUES (102, 'bananas');
INSERT INTO [Junction] (mid, pid) VALUES (1,101);
INSERT INTO [Junction] (mid, pid) VALUES (1,102);
INSERT INTO [Junction] (mid, pid) VALUES (2,102);

create view v_junction
as
select j.jid,
              m.id mid,
              p.id pid,
              m.name mer_name,
          p.description
from Junction j
join Merchants m
on j.mid = m.id
join Products p
on j.pid=p.id

in the aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GridViewForJunctionTable.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       
    <asp:GridView runat="server" 
        AutoGenerateColumns="False" 
        DataKeyNames="jid" 
        OnRowCommand="GridView1_RowCommand"
        ID="GridView1"
        AutoGenerateEditButton="true"
        OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
        
        >
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%#Eval("mid") %>' ID="LblMid" Visible="false"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%#Eval("pid") %>' ID="LblPid" Visible="false"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="MerName">
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%#Eval("mer_name") %>' ID="LblMerName"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" Text='<%#Eval("mer_name") %>' ID="TxtMerName"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Description">
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%#Eval("description") %>' ID="LblDescription"></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" Text='<%#Eval("description") %>' ID="TxtDescription"></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" OnClientClick="return confirm('Are sure to delete it?')" Text="Delete"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

In the aspx.cs file:

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

namespace GridViewForJunctionTable
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
        private void BindGridView()
        {
            using (DemoDBEntities ctx = new DemoDBEntities())
            {
                var query = from q in ctx.v_junction
                            select q;
                GridView1.DataSource = query.ToList();
                GridView1.DataBind();
            }
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            
            if (e.CommandName == "Delete")
            {
                GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer; 
                string jid = GridView1.DataKeys[row.RowIndex].Value.ToString();
                Label lblMerID = (Label)row.FindControl("LblMid");
                Label lblPid = (Label)row.FindControl("LblPid");
                //now you can use these ID to delete data...
            }
        }


        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGridView();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Label lblMerID = (Label)GridView1.Rows[e.RowIndex].FindControl("LblMid");
            Label lblPID = (Label)GridView1.Rows[e.RowIndex].FindControl("LblPid");
            TextBox TxtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtMerName");
            TextBox TxtDescription = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtDescription");
            string jid = GridView1.DataKeys[e.RowIndex].Value.ToString();
            //Now you can use thest ID and text to update the data...
        }
    }
}

Hope it can help you.

If there is anything unclear, please let me know.

Best Regards,
Terry Guo

Thanks a ton Terry!  I was hoping to do it with an EntityDataSource (no code behind), but so far, still no luck. 

I’ll rework it to see if I can use your example instead.