jamheadart
jamheadart

Reputation: 5323

asp.net DetailsView allowing ID / PK entry

I've got a DetailsView which is defaulted to insert mode:

<asp:DetailsView runat="server" DataSourceID="SqlDataSource"
    AutoGenerateInsertButton="true" DefaultMode="Insert"
    DataKeyNames="ID"></asp:DetailsView>

The issue being that the input for ID is editable, i.e. a user can input an ID. Entering an ID does nothing on the actual update command, but a user shouldn't think he can put their own ID in the first place. I don't have ID as an InputParameter nor is it included in the actual SQL command in the code-behind.

On a GridView that uses the same SqlDataSource, I easily disabled ID editing using the DataKeyNames="ID" attribute but this doesn't seem to have worked for the DetailsView - any ideas how to prevent a user editing the ID field?


EDIT: I've just added an ID attribute, AutoGenerateRows="true" and EnableModelValidation="true" and still nothing preventing user from toying with the ID field.

Upvotes: 0

Views: 67

Answers (1)

RobJarvis
RobJarvis

Reputation: 370

Here is an example from Microsoft Help:

<asp:DetailsView ID="CustomerDetail" 
        DataSourceID="Details" AutoGenerateRows="false"
        AutoGenerateInsertButton="true" 
        AutoGenerateEditButton="true" 
        AutoGenerateDeleteButton="true"
        EmptyDataText="No records." 
        DataKeyNames="CustomerID" GridLines="Both" 
        OnItemInserted="CustomerDetail_ItemInserted"
        OnItemInserting="CustomerDetail_ItemInserting" 
        OnItemUpdated="CustomerDetail_ItemUpdated"
        OnItemUpdating="CustomerDetail_ItemUpdating" 
        OnItemDeleted="CustomerDetail_ItemDeleted"
        runat="server">
        <HeaderStyle BackColor="Navy" ForeColor="White" />
        <RowStyle BackColor="White" />
        <AlternatingRowStyle BackColor="LightGray" />
        <EditRowStyle BackColor="LightCyan" />
        <Fields>
          <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" />
          <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
          <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle" />
          <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
          <asp:BoundField DataField="Address" HeaderText="Address" />
          <asp:BoundField DataField="City" HeaderText="City" />
          <asp:BoundField DataField="Region" HeaderText="Region" />
          <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
          <asp:BoundField DataField="Country" HeaderText="Country" />
          <asp:BoundField DataField="Phone" HeaderText="Phone" />
          <asp:BoundField DataField="Fax" HeaderText="Fax" />
        </Fields>
      </asp:DetailsView>

Note under <Fields>, the first field has a ReadOnly="True" attribute. Try that.

Upvotes: 1

Related Questions