开发者

How to do a data lookup field in a DetailsView?

I have a master-detail page for Customers. Select a customer from the list and a details view opens with Name, Address开发者_高级运维...etc.

I've been asked to add a field listing the Sales Rep servicing that customer.

I want the new field to hold the foreign key to the SalesRep table: the SalesRepID. An integer.

I am not sure how to "wire up" the ItemTemplate field for displaying the Sales Rep name in a label. Also not sure about the EditItemTemplate dropdown list of possible Sales Reps.

I know I need to create a datasource to retreive the Sales Reps into a dataSet.

Let's call it "SQL_Reps_source".

A DropDownList seems to only like a list of values, and doesn't seem to handle Keys and Values like a HashTable or SortedList would.

Any advice on how to go about this?

Thanks


The following example adds a DropDownList to the EditItemTemplate of the DetailsView. The DataSourceID is set to the data source control that retrieves the sales reps names and id's.

<asp:TemplateField HeaderText="Sales Rep">
    <EditItemTemplate>
        <asp:SqlDataSource ID="SqlDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
            SelectCommand="SELECT SalesRepID, SalesRepName FROM SalesReps">
        </asp:SqlDataSource>
        <asp:DropDownList ID="DropDownList" Runat="server" 
            DataTextField="SalesRepName" DataValueField="SalesRepID"     
            SelectedValue='<%# Bind("SalesRepID") %>'
            DataSourceID="SqlDataSource">
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label" Runat="server" 
            Text='<%# Bind("SalesRepName") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>


  1. For display purposes - return the NAME of the Sales Rep. rather than ID

  2. DropDownList (ddl) handles both Values and Keys just fine, the naming is a bit off though. ddl.DataTextField property will hold the Name, ddl.DataValueField property will hold the ID. (see this answer for more details on this)

  3. In the EditTemplate you'd need to fill the DropDown as described above, and then set its SelectedValue to the ID of Sales Rep. in quesion.

Hope this helps.


When you bind the dropdownlist do this:

ddl.DataSource = SQL_Reps_source;
ddl..DataTextField = "fullname";
ddl..DataValueField = "id";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜