Reputation: 21
All the data is displayed correctly. Only the "Update" link isn't working. My code is:
<asp:SqlDataSource runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
DataSourceMode="DataReader" ID="DataFrom"
SelectCommand="SELECT * FROM Classes" DeleteCommand="DELETE FROM Classes WHERE Id=@Id"
UpdateCommand="UPDATE Classes SET Password=@Password, Name=@Name WHERE Id=@Id">
<DeleteParameters><asp:Parameter Name="Id" /></DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Id" />
<asp:Parameter Name="Password" Type="String" /><asp:Parameter Name="Name" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView runat="server" ID="Main" DataSourceID="DataFrom" AutoGenerateColumns="false" AllowSorting="True" DataKeyNames="Id,Password,Name"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Class ID" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Password" HeaderText="Password" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
Upvotes: 2
Views: 2197
Reputation: 10565
You must take care of below points:
The GridView & hence the DataSource never allows changing of the Columns which are specified in DataKeyNames
property.
Don't try to update a PrimaryKey column. This will not be allowed. Although No error will be shown on clicking update, but if you check the values in Database, changes aren't applied.
Make sure your Update command is not trying to set a NEW value for Primary key. as a result, complete Update command will be rejected if you even try to set a Primary Key. i.e. even other Non- Primary key columns will not be changed. So if Id
is a primary Key, below update command will be rejected if you specify new value for Id
:
UpdateCommand="UPDATE Classes SET Id=@Id,Password=@Password,Name=@Name WHERE Id=@Id"
So in your case, I guess, Id
must be a primaryKey. set the property DataKeyNames as:
DataKeyNames="Id".
Because, you want to update Name & Password, so don't include them in DataKeyNames. What's important is that usually you should mention only the PrimaryKeys in DatKeyNames
property.
Rest of Your UpdateCommand is completely fine.
Upvotes: 2