Category Archives: EntityDataSource

[RESOLVED] Page connetcion

Hi,

I am trying make a site using web form. I have three table, that i want to connect to. I have a product, categories and product type tables. in my main page i am using the category table to generate the list menu. Now i want to use, the product type, to generate a page with product type, which will in turn lead to a page with  the products. I have the typeid in the product as well as in the product type table.  i would like it to display the  type from my database on a page of it's own. how do i call such that the product types are show on page, when i call the page from list menu.

How your Category and Product Type tables connected?

Try placing timer in updatepanel

They are not connect, they are only connected through the product table, where there primary keys are listed.

 

They are not connect, they are only connected through the product table, where there primary keys are listed.

 

 

How do i do that ? i am relatively new at asp.net

mudassarkhan

Try placing timer in updatepanel

 

Hi Ceddy,

So you got your table ready in the database, and want to display it to ASP.NET web form?

It's not that simple.

First, you need to make a connection between the webpage and the database.

Second, you need to learn about gridview (or datagrid) to bind the table information to the page.

For example, this is the way how I interact with the database.

EXAMPLE- BIND THE DROPDOWNLIST from the data in a table in MSSQL 2008 CODE BEHIND:

/* Wook. DropDownRegion Function */
    void BindDropDownRegion()
    {
            //This connection string is declared in the web.config file
            SqlConnection con = new
            SqlConnection(ConfigurationManager.ConnectionStrings["DB3ConnectionString"].ConnectionString);
            
            //Sql Command for the database
            SqlCommand cmd = new SqlCommand("SELECT MCWRegionID,\"Desc\" FROM MCWRegion", con);

        //Open connection.
        con.Open();
        //Read data
        SqlDataReader rd = cmd.ExecuteReader();

        //Bind Information on the dropdown
        DropDownRegion.Items.Add("<Select Region>");
        DropDownRegion.SelectedIndex = 0;
        DropDownRegion.DataSource = rd;
        DropDownRegion.DataValueField = "MCWRegionID";
        DropDownRegion.DataTextField = "desc";
        DropDownRegion.DataBind();
        
        //Close connection. Make sure you close every connection
        rd.Close();
        con.Close();
        cmd.Connection.Close();
    }

HTML part:

<td style="height: 26px">
                   <!--DropDown Region-->
                   <asp:DropDownList ID="DropDownRegion"
                    runat="server" AutoPostBack="false" appenddatabounditems="True"
                    Width="200px" style="margin-left:0px">                                                               
                   </asp:DropDownList>
</td>

Result:

 

 

 

 

 

 

 

Cool right?

Ask me if you have any other question Wink

 

Your categories and product type tables must be connected thru primary key/foreign key relations, so when you will click list menu,  you will get categoryID(for instance) and post it to product type page where you should get product types using categoryId. from there you can use same approach relatively to product type and products, just this time you should post typeid to products page where again using typeid retrieve products and display it in your page.

Category.aspx -- redirect to --> ProductTypes.aspx --redirect to --> Products.aspx

to send categoryId and typeId between pages you can use Session object or query strings, or CrossPagePostBack technique.

<div>Sorry taking so long to reply, that is exactly i am trying to do. I am new at this could you show me an example. so far i am able to connect from category and products. this my code. thanks</div> <div> <div><</div> <div> </div> <div> </div> </div> <div>asp:ListView ID="ListView_ProductsMenu" runat="server" DataKeyNames="CategoryId"</div> <div>  </div>

<div></div> <div> </div>

<div>DataSourceID="EDS_Category_Menu"></div> <div>  </div>

<div> </div> <div> </div>

<div><EmptyDataTemplate>No Menu Items.</EmptyDataTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div><ItemSeparatorTemplate></ItemSeparatorTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div><ItemTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div><li></div> <div>  </div>

<div> </div> <div> </div>

<div><a href='<%# VirtualPathUtility.ToAbsolute("~/ProductsList.aspx?CategoryId=" +</div> <div> </div>

<div> Eval ("CategoryId")) %></div> <div> </div>

<div>'><%# Eval("Category1") %></a></li></div> <div>  </div>

<div> </div> <div> </div>

<div></ItemTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div><LayoutTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div><ul id="itemPlaceHolderContainer" runat="server"</div> <div>  </div>

<div> </div> <div> </div>

<div>style="font-family: Verdana, Arial, Helvetica, Sans-Serif"></div> <div>  </div>

<div> </div> <div> </div>

<div><li runat="server" id="itemPlaceholder" /></div> <div>  </div>

<div> </div> <div> </div>

<div></ul></div> <div>  </div>

<div> </div> <div> </div>

<div><div style="text-align: center; background-color: #ffcc66; font-family: Verdana, Arial, Helvetica,</div> <div> </div>

<div> sans-serif; </div> <div> </div> <div> </div>

<div>color:#333333"></div> <div>  </div>

<div> </div> <div> </div>

<div></div></div> <div>  </div>

<div> </div> <div> </div>

<div></LayoutTemplate></div> <div>  </div>

<div> </div> <div> </div>

<div></asp:ListView></div> <div>  </div>

<div> </div> <div> </div>

<div><asp:EntityDataSource ID="EDS_Category_Menu" runat="server" </div> <div> </div>

<div> </div> <div> </div>

<div>ConnectionString="name=Henper_DbEntities" </div> <div> </div>

<div> </div> <div> </div>

<div>DefaultContainerName="Henper_DbEntities" EnableFlattening="False" </div> <div> </div>

<div> </div> <div> </div>

<div>EntitySetName="Categories"></div> <div>  </div>

<div> </div> <div> </div>

<div></asp:EntityDataSource></div> <div> </div>

in your next page use the following

<a href='<%# VirtualPathUtility.ToAbsolute("~/ProductsList.aspx?CategoryId=" +

Eval ("TypeId")) %>
if you noticed this time page will pass TypeId to next page, where retrieve TypeId from query string and use it in your query to retrieve data, and bind ListView.

Thanks for you quick responce,

in this case should i make the Product type table as the entity course ? I am abit confused  how i will get it to show only the product types on it's own  page and then redirecting to the products.

for example.

Under categories i have jewellery after that i should show the types of Jewellery i have e.g. Necklaces, Earings and complete set. from here they should be able to choose one and be redirected to the page with only the specific type chosen  where the different products are all located.

thanks in advance.

the reson i am asking is because i only have the typeid and categoryId in the products table.  how will i be able to show the product types plus their names if i have no direct relation.

metadata error msg

I am following the tutorial in http://www.asp.net/general/videos/5-minute-introduction-to-aspnet-web-forms

Around 02:46 into the video, instructions are given to configure the entity data source by selecting a database.

In the connection string, named connection option, after I enter in the named connection (there is only one option which I created earlier as part of the web config existing connection), I get the following error msg:

"The metadata specified in the connection string could not be loaded. Consider rebuilding the web project to build assemblies that may contain metadata. The following error(s) occurred: Unable to load the specified metadata resource."

I set up a new project just to make sure, but this error came up again.

Any ideas?

<div class="header comment_microsoft"></div> <div class="header comment_microsoft">"Posted by Microsoft on 10/05/2011 at 10:51</div>

Please try adding a database to your project using the following steps:

1. Right-mouse click on the App_Data folder and select Add -> New Item..
2. Choose the "Data" node in the tree-view on the left
3. Select "SQL Server Database" in the item list, enter a name in the textbox at the bottom, and click "Add"
4. Double-click on the *.mdf file addedd in the previous step (it will be in the App_Data folder of your project). This will bring up the Server Explorer tool window.
5. Use the features of the Server Explorer tool window to add tables to your database
6. Once you've created your database, you can now add an Entity Model which is generated from this database, following the steps in the video."

Not quite sure I understand this and I'm a little confused about which step is first. What is the first stage before this? Alternatively, is there anything written down that explains the whole process correctly? I am trying to connect tables from an existing SQL Server database.

[RESOLVED] Dynamically add item to DropDownList

I have an Edit page in my application that contains a DropDownList.

This DDL is bound to an EntityDataSource that only shows the active "ProjectManagers".

In the case where the user is editing a record that is assigned to an "inactive" ProjectManger, an "ArgumentOutOfRange" Exception is (rightfully) thrown by the DDL (because that Item wan't bound to the list, since it only binds "Active" ProjectManagers).

So, I need to add this item to the DropDownList dynamically or at least add an "Inactive" item and then "select" that item in the code behind. (Although, adding an "Inactive" item would force the user to actually change the ProjectManager and that wouldn't be a good idea.)

I have tried handling the OnDataBinding method with the following code:

 

protected void PreventErrorOnBinding(object sender, EventArgs e)
    {
        DropDownList theDropDownList = (DropDownList)sender;
        theDropDownList.DataBinding -= new EventHandler(PreventErrorOnbinding);
        theDropDownList.AppendDataBoundItems = true;
        ListItem li = new ListItem(""<<Inactive>>", "0");
        theDropDownList.Items.Insert(0, li);
        try
        {
            theDropDownList.DataBind();
        }
        catch (ArgumentOutOfRangeException)
        {
            theDropDownList.SelectedValue = "0";
        }
    }

 

It seems to work, with one exception. My dropdownlist is "doubled". All of the Items are repeated. ie 1-8 then 1-8 again. It is somehow binding the items twice.

Also, (if I can get this working or find a better solution) I need get the (ProjectManagerID) value (the selected value or the actual column from the Entity Context). I have thought about handling the OnContextCreated event of the EDS and getting it that way or would it be better (seems easier) to setup a local variable and in the markup do something like "SelectedValue='<%# SaveValue(DataBinder.Eval(ContainerDataItem,"ProjectManagerID")) %>', then in the code behind I would save the "ProjectManagerID" to a locally defined variable (which I could then access in the "OnBinding" event code above...asumming that code fires after the Eval... and I think it would...).

Any thoughts to either of these problems?

Thanks for the help again folks!
Shayne

Hi,

The reason that you get double items in the dropdown must be that the binding code is being called twice somehow. Maybe you could check if you have the "If Page.IsPostback..." in the correct place. An easier solution would be to clear the dropdown list just before you bind data to it.


Like this:

protected void PreventErrorOnBinding(object sender, EventArgs e)
    {
        DropDownList theDropDownList = (DropDownList)sender;
        theDropDownList.DataBinding -= new EventHandler(PreventErrorOnbinding);
        theDropDownList.AppendDataBoundItems = true;

        theDropDownList.Clear();

        ListItem li = new ListItem(""<<Inactive>>", "0");
        theDropDownList.Items.Insert(0, li);
        try

        {
            theDropDownList.DataBind();
        }
        catch (ArgumentOutOfRangeException)
        {
            theDropDownList.SelectedValue = "0";
        }
    }

Actually, I did try adding that! So, it has to be binding AGAIN after this! 

Try to check if the list contains any items before adding items to it, something like this:


If theDropDownList.Items.Count() < 1 Then

'add items

End If

I use VB syntax now you have to convert to C#.

Also check that your database query isnt returning double results.


I dont have an "If Page.IsPostback...". 

The query only returns single results, because it works when I stop handling the OnDataBind (also I checked in the Debugger).

 

When I leave this method, I do a Quick Watch on  "theDropDownList.Items.Count" and it is 13, but when the page renders there are 26 items in the DDL. Something is appending items after this method.

Make sure your AppendDataBoundItems="False" for the dropdown.

Its the Insert. That is where my items are being doubled.... 

Here is how my ddl are built in the code behind.

DataSet dsManufac = getManufac();


            ddlReportManuFilter.DataSource = dsManufac;
            ddlReportManuFilter.DataTextField = "Manufact";
            ddlReportManuFilter.DataValueField = "Manufact";
            ddlReportManuFilter.Items.Clear();
            ddlReportManuFilter.Items.Insert(0, new ListItem("Please Select Manufacturer to Filter Results", "%"));
            ddlReportManuFilter.DataBind();


And this is my setup on the ASPX

<asp:DropDownList ID="ddlReportManuFilter" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlReportManuFilter_SelectedIndexChanged" AppendDataBoundItems="True" />

cubangt

Make sure your AppendDataBoundItems="False" for the dropdown.

 

 

When I do this, I get the ArgumentOutOfRangeException exception. Something is obviusly binding these values again after the method.

 

I retract my previous statement. The items are NOT being doubled by the Insert statement. I was looking at the capacity, not the count. The count only increases by one after the Insert.

cubangt

Here is how my ddl are built in the code behind.

<div class=dp-highlighter> <div class=bar> <div class=tools>view plaincopy to clipboardprint?</div></div>
  1. DataSet dsManufac = getManufac();   
  2.   
  3. ddlReportManuFilter.DataSource = dsManufac;   
  4. ddlReportManuFilter.DataTextField = "Manufact";   
  5. ddlReportManuFilter.DataValueField = "Manufact";   
  6. ddlReportManuFilter.Items.Clear();   
  7. ddlReportManuFilter.Items.Insert(0, new ListItem("Please Select Manufacturer to Filter Results""%"));   
  8. ddlReportManuFilter.DataBind();  
</div>
DataSet dsManufac = getManufac();


            ddlReportManuFilter.DataSource = dsManufac;
            ddlReportManuFilter.DataTextField = "Manufact";
            ddlReportManuFilter.DataValueField = "Manufact";
            ddlReportManuFilter.Items.Clear();
            ddlReportManuFilter.Items.Insert(0, new ListItem("Please Select Manufacturer to Filter Results", "%"));
            ddlReportManuFilter.DataBind();


And this is my setup on the ASPX

<asp:DropDownList ID="ddlReportManuFilter" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlReportManuFilter_SelectedIndexChanged" AppendDataBoundItems="True" />

 

 

 

 

I appreciate the attempt, but that doesn't address my issue at all. You see, the problem I have is the value is already present, it is just bound to a record in the table that isn't loaded in the DDL, because it has since become Inactive.

 

So are you wanting to disable that item in the dropdown so it cant be selected? If so, i had a post a while that that i was doing the same thing and someone helped with that.  

 No.... I guess I didnt explain it well in my post, sorry.

The dropdownlist is bound to a datasource that only loads records from the ProjectManger table that are "Active".

If a record is opened (in the FormView) on this edit page that was assigned a ProjectManager that is no longer active, the DDL throws an exception (because, that item isn't in the list since only currently active items are bound). So, I am trying to manuall add that item to the list.

I just read about another possibility.

 

I may just create my own Custom Control "MyDropDownList", which inherits from DropDownList and override the PerformDataBind function so I can catch the "ArgumentOutOfRangeException" event. Although, on second thought that still doesnt help me solve the real problem. I REALLY want to add the selection to the DDL.

 

I may just rethink the whole thing and instead of binding ONLY the Active Project Mangers, bind them all, but for the Active ones have them appear in the list at the bottom. Something like:

Barack Obama
George Bush
Albert Einstein (InActive)
John F Kennedy (InActive)

etc.. this would insure I would never get the exception. I just hate giving the user all those "Inactive" options. Although, I can eliminate them in my Add page, since there is nothing to bind to. I guess it isn't the end of the world to have them on the Edit Page.

 

OK, just throwing this out there.. but why not add your item to the dropdown like so

theDropDownList.Items.Insert(0, new ListItem("<<INACTIVE>>""0")); 

 

Then in your code behind, you check that value on binding and if the value is not an active record(not in list), the defaultvalue of the dropdown is <<INACTIVE>>

Just an idea..since you dont really want to display the actual inactive names.. you could check if that individual records value is in the list, if its not then default it to the inactive line you added.

 

 

 

 

The thing is. I do want to display the name. Lets say the user needs to edit another field on this record. I dont want them to HAVE to change the Project Manger, just becuase the PM is inactive when they edit the record, it was STILL the PM at the time the Job as started/completed.

 

I am just going to use the approach of including all the PMs and for those that are inactive I put them at the bottom of the list such as: "John Doe (Inactive)". 

To avoid duplicates, add e.Cancel=true to the selecting event of the datasource for the dropdownlist if the selected value is in the list of items. Add e.Cancel = false if the selected value is not in the list of items.

www.castnerit.com.au

[RESOLVED] Hyperlink redirect

Dear Friends,

I'm building a products website, I made a page where I can add products, everything is going great with me except at the end where I put a hyperlink that pressing on it suppose to take me to a page where I can add photos to this product, but I really don't know how to use this link to redirect to another page

my "AddProduct" page code is:

<%@ Page Title="AddProduct" Language="C#" MasterPageFile="~/Admin/Admin.master" AutoEventWireup="true" CodeFile="AddProduct.aspx.cs" Inherits="Admin_AddProduct" %>

<asp:Content ID="HeadContent" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="EntryBodyContent" ContentPlaceHolderID="EntryBodyPlaceHolder" Runat="Server">
    <asp:Panel ID="ProductDetailsPanel" runat="server" Visible="true">
        <div>
            <h1>AddProduct</h1>
            <table cellpadding="0" cellspacing="15" id="ProductDetailsTable" width="90%">
                <tbody>
                    <tr>
                        <td class="RightTD">
                            <asp:Label ID="CategoryLabel" runat="server" AssociatedControlID="CategoriesDDL" Text="Category"></asp:Label>
                        </td>
                        <td class="LeftTD">
                            <asp:DropDownList ID="CategoriesDDL" runat="server"
                            AppendDataBoundItems="True"
                            CssClass="DDLCategories"
                            DataSourceID="CategoriesEntityDataSource"
                            DataTextField="CategoryName"
                            DataValueField="ID">
                                <asp:ListItem>Choose category ---------------------------------------------</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="CategoriesDDLValidator" runat="server" ControlToValidate="CategoriesDDL" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" InitialValue="اختر فئة ---------------------------------------------" />
                            <asp:EntityDataSource ID="CategoriesEntityDataSource" runat="server"
                                ConnectionString="name=HEdbEntities"
                                DefaultContainerName="HEdbEntities"
                                EnableFlattening="False"
                                EntitySetName="Categories"
                                Select="it.[CategoryName], it.[ID]">
                            </asp:EntityDataSource>
                        </td>
                    </tr>
                    <tr>
                        <td class="RightTD">
                            <asp:Label ID="OriginLabel" runat="server" AssociatedControlID="OriginsDDL" Text="Country"></asp:Label>
                        </td>
                        <td>
                            <asp:DropDownList ID="OriginsDDL" runat="server"
                            AppendDataBoundItems="True"
                            CssClass="DDLOrigins"
                            DataSourceID="OriginsEntityDataSource"
                            DataTextField="OriginName"
                            DataValueField="ID">
                                <asp:ListItem>Choose country ---------------------------------------</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="OriginsDDLValidator" runat="server" ControlToValidate="OriginsDDL" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" InitialValue="اختر بلد منشأ ---------------------------------------" />
                            <asp:EntityDataSource ID="OriginsEntityDataSource" runat="server"
                                ConnectionString="name=HEdbEntities"
                                DefaultContainerName="HEdbEntities"
                                EnableFlattening="False"
                                EntitySetName="Origins"
                                Select="it.[OriginName], it.[ID]">
                            </asp:EntityDataSource>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ProductNameLabel" runat="server" Text="Product name" AssociatedControlID="ProductNameTextBox"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ProductNameTextBox" runat="server" CssClass="ProductNameTextBox"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ProductNameTextBoxValidator" runat="server" ControlToValidate="ProductNameTextBox" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ProductModelLabel" runat="server" Text="Product model" AssociatedControlID="ProductModelTextBox"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ProductModelTextBox" runat="server" CssClass="ProductModelTextBox"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ProductModelTextBoxValidator" runat="server" ControlToValidate="ProductModelTextBox" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ProductSummaryLabel" runat="server" Text="Product summaryة" AssociatedControlID="ProductSummaryTextBox"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ProductSummaryTextBox" runat="server" CssClass="ProductSummaryTextBox" TextMode="MultiLine"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ProductSummaryTextBoxValidator" runat="server" ControlToValidate="ProductSummaryTextBox" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ProductDetailsLabel" runat="server" Text="Product details" AssociatedControlID="ProductDetailsTextBox"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ProductDetailsTextBox" runat="server" CssClass="ProductDetailsTextBox" TextMode="MultiLine"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="ProductDetailsTextBoxValidator" runat="server" ControlToValidate="ProductDetailsTextBox" Display="Dynamic" ErrorMessage="*" ForeColor="#ff0000" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ProductStateLabel" runat="server" Text="Publish product" AssociatedControlID="ProductStateCheckBox"></asp:Label>
                        </td>
                        <td>
                            <asp:CheckBox ID="ProductStateCheckBox" runat="server" Checked="true" />
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>
                            <asp:Button ID="AddButton" runat="server" CssClass="AddButton" OnClick="AddButton_Click" Text="Add" />
                            <asp:Button ID="CancelButton" runat="server" CssClass="CancelButton" OnClick="CancelButton_Click" Text="Cancel" />
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </asp:Panel>
    <asp:Panel ID="ProductAddedSuccessfulPanel" runat="server" Visible="false">
        <div>
            <table cellpadding="0" cellspacing="15" id="ProductAddedSuccessfulTable" width="90%">
                <tr>
                    <td>Product added successfuly</td>
                </tr>
                <tr>
                    <td><asp:hyperlink ID="AddPhotosLimk" runat="server" Text"Add photos to this product" /></td>
                </tr>
            </table>
        </div>
        <div>
            <p>&nbsp;</p>
        </div>
    </asp:Panel>
</asp:Content>

 

and the code behind is:

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

public partial class Admin_AddProduct : System.Web.UI.Page
{
    int _iD = -1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString.Get("ID")))
        {
            _iD = Convert.ToInt32(Request.QueryString.Get("ID"));
        }
        if (!Page.IsPostBack && _iD > -1)
        {
            using (HEdbEntities myEntities = new HEdbEntities())
            {
                var product = (from p in myEntities.Products
                               where p.ID == _iD
                               select p).SingleOrDefault();
                if (product != null)
                {
                    CategoriesDDL.DataBind();
                    ListItem categoryItem = CategoriesDDL.Items.FindByValue(product.CategoryID.ToString());
                    if (categoryItem != null)
                    {
                        categoryItem.Selected = true;
                    }
                    OriginsDDL.DataBind();
                    ListItem originItem = OriginsDDL.Items.FindByValue(product.OriginID.ToString());
                    if (originItem != null)
                    {
                        originItem.Selected = true;
                    }
                    ProductNameTextBox.Text = product.ProductName;
                    ProductModelTextBox.Text = product.ProductModel;
                    ProductSummaryTextBox.Text = product.ProductSummary;
                    ProductDetailsTextBox.Text = product.ProductDetails;
                    ProductStateCheckBox.Checked = product.ProductState;
                }
            }
        }
    }

    protected void AddButton_Click(object sender, EventArgs e)
    {
        using (HEdbEntities myEntities = new HEdbEntities())
        {
            Product myProduct;
            if (_iD == -1) // Insert new item
            {
                myProduct = new Product();
                myEntities.AddToProducts(myProduct);
            }
            else // update existing item
            {
                myProduct = (from p in myEntities.Products
                             where p.ID == _iD
                             select p).Single();
            }
            myProduct.CategoryID = Convert.ToInt32(CategoriesDDL.SelectedValue);
            myProduct.OriginID = Convert.ToInt32(OriginsDDL.SelectedValue);
            myProduct.ProductName = ProductNameTextBox.Text;
            myProduct.ProductModel = ProductModelTextBox.Text;
            myProduct.ProductSummary = ProductSummaryTextBox.Text;
            myProduct.ProductDetails = ProductDetailsTextBox.Text;
            myProduct.ProductState = ProductStateCheckBox.Checked;
            myEntities.SaveChanges();
        }
        ProductDetailsPanel.Visible = false;
        ProductAddedSuccessfulPanel.Visible = true;
    }

    protected void CancelButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("Admin.aspx");
    }
}

 

So please can anyone help me in this

Thank you so much in advance

 

Does the hyperlink have to do anything else?  Like do you need to run some logic in code behind before the redirect, or simply redirect to somepage.aspx?

The asp:Hyperlink class has the NavigateUrl property that you can use to set it to any location:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.navigateurl.aspx

<asp:hyperlink ID="AddPhotosLink" runat="server" Text"Add photos to this product" NavigateUrl="addPhotos.aspx" />

or, if you need the link to be conditional based on the actual id, you can set that property in code-behind Page_Load:

AddPhotosLink.NavigateUrl="addPhotos.aspx?id="+someId;

I just want to redirect thorough the hyperlink to a page where I can add some photos to a certain id.

I couldn't put the property you mentioned in the code-behinde page, please can ypu tell me specificaly where should I put it.

you should be able to set that in the Page_Load

Have you created the page on which you add the photos? If not, you will need to do so first. Then, redirect the HyperLink to the appropriate page.

[RESOLVED] DropDownLIst and EntityDataSource issue

Dear freinds,
 
I'm trying to build a products gridview with a dropdwonlist for categories, where when somebody chose a category all its products will appeare in the grid view using EntityDataSource.
 
My problem is I want to make the default option for the dropdownlist is "Choose category", but I coudn't do that using EntityDataSource,

<div id="ChooseCategoryDIV">
        <table cellpadding="0" cellspacing="0" width="90%">
            <tbody>
                <tr>
                    <td>
                        <asp:DropDownList ID="CategoriesDDL" runat="server"
                            AutoPostBack="True"
                            CssClass="DDLCategories"
                            DataSourceID="CategoriesEntityDataSource"
                            DataTextField="CategoryName"
                            DataValueField="ID">
                            <asp:ListItem>Choose category ---------------------------------------------</asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="ShowProductsDIV">
        <table cellpadding="0" cellspacing="0" width="90%">
            <tbody>
                <tr>
                    <td>
                        <asp:GridView ID="ProductsGridView" runat="server"
                            AutoGenerateColumns="False"
                            DataKeyNames="ID"
                            DataSourceID="ProductsEntityDataSource">
                            <Columns>
                                <asp:CommandField ShowDeleteButton="True" />
                                <asp:TemplateField HeaderText="OriginID" SortExpression="OriginID">
                                    <ItemTemplate>
                                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("OriginID") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField DataField="ProductName" HeaderText="ProductName"
                                    SortExpression="ProductName" />
                                <asp:BoundField DataField="ProductModel" HeaderText="ProductModel"
                                    SortExpression="ProductModel" />
                                <asp:CheckBoxField DataField="ProductState" HeaderText="ProductState"
                                    SortExpression="ProductState" />
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="CategoriesEntityDataSourceDIV">
        <asp:EntityDataSource ID="CategoriesEntityDataSource" runat="server"
            ConnectionString="name=HEdbEntities"
            DefaultContainerName="HEdbEntities"
            EnableFlattening="False"
            EntitySetName="Categories"
            Select="it.[ID], it.[CategoryName]">
        </asp:EntityDataSource>
    </div>
    <div id="ProductssEntityDataSourceDIV">
        <asp:EntityDataSource ID="ProductsEntityDataSource" runat="server"
            AutoGenerateWhereClause="True"
            ConnectionString="name=HEdbEntities"
            DefaultContainerName="HEdbEntities"
            EnableDelete="True"
            EnableFlattening="False"
            EntitySetName="Products"
            Where="">
            <WhereParameters>
                <asp:ControlParameter ControlID="CategoriesDDL" Name="CategoryID" PropertyName="SelectedValue" Type="Int32" />
            </WhereParameters>
        </asp:EntityDataSource>
    </div>

 

So please can you help me in that.

Add AppendDataBoundItems Property to true for that dropdown. Like this..

<asp:DropDownList ID="CategoriesDDL" runat="server" AutoPostBack="True"
CssClass="DDLCategories" AppendDataBoundItems="true"
DataSourceID="CategoriesEntityDataSource" DataTextField="CategoryName" DataValueField="ID">
<asp:ListItem>Choose category </asp:ListItem>
</asp:DropDownList>

I did that, but it doesn't work, it keep telling me that the format is not correct.

Hi,

In order to resolve your issue, I will give you a sample. Hope this will help.

In the .aspx, add the parameter  AppendDataBoundItems="true".

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dropdownlist_EntityDataSource.aspx.cs" Inherits="dropdownlist_EntityDataSource" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server"  AutoPostBack="true"
            DataSourceID="EntityDataSource1" DataTextField="sname" DataValueField="sname"
             AppendDataBoundItems="true">

        </asp:DropDownList>
        <asp:EntityDataSource ID="EntityDataSource1" runat="server"
            ConnectionString="name=aaEntities" DefaultContainerName="aaEntities"
            EnableFlattening="False" EntitySetName="stu">
        </asp:EntityDataSource>
    </div>
    </form>
</body>
</html>

In the .cs, please don't forget to add  the corresponding ListItem to DropDownList1 as below.

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

public partial class dropdownlist_EntityDataSource : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {              
           
        DropDownList1.Items.Add(new ListItem("-- Please select one --", ""));
                }
}
}

In addition, I would recommend that please check the link below for more information about the AppendDataBoundItems Property of DropDownList in ASP.NET.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx

 Please try to modify it to meet your requirement. In my opinion, you can resolve your issue through the method above. If I have anything misunderstood, please let me know.

Thank you so much