PDA

View Full Version : UDPATE/DELETE queries causing GridView control to throw odd exceptions


chump2877
09-12-2007, 02:47 PM
OK ASP.NET experts, I've been struggling with a problem for awhile I need your help resolving it...

I've got a SQL-databound GridView control that is throwing an exception any time I try to update/delete a row...

on UPDATE:

You have specified that your update command compares all values on SqlDataSource 'dsStudents', but the dictionary passed in for oldValues is empty. Pass in a valid dictionary for update or change your mode to OverwriteChanges.


on DELETE:

You have specified that your delete command compares all values on SqlDataSource 'dsStudents', but the dictionary passed in for values is empty. Pass in a valid dictionary for delete or change your mode to OverwriteChanges.


I am completely stumped here, as my code looks OK to me...Huge thanks (and reps) will be given to anyone who can spot the error in my code! Here is my code:

Students.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Students.aspx.cs" Inherits="Week12.Students" %>
<!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>Student GridView</title>
<link type="text/css" rel="Stylesheet" href="Students.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvStudents" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="StudentId" DataSourceID="dsStudents" ForeColor="#333333" GridLines="None" PageSize="5" ShowFooter="True" OnRowCommand="gvStudents_RowCommand" OnRowDeleted="gvStudents_RowDeleted" OnRowUpdated="gvStudents_RowUpdated">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnUpdateStudent" runat="server" CommandName="Update" Text="Update" ValidationGroup="Update" />
<asp:Button ID="btnCancelEdit" runat="server" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEditStudent" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="btnDeleteStudent" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddStudent" runat="server" CommandName="Insert" Text="Add Student" ValidationGroup="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="StudentId">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddStudentId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="ID is a required field." ControlToValidate="tbAddStudentId" SetFocusOnError="true" Display="None" ValidationGroup="Add"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="You entered an invalid ID." ControlToValidate="tbAddStudentId" SetFocusOnError="true" ValidationExpression="^[A-Z]{2}\d{4}$" Display="None" ValidationGroup="Add"></asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Eval("FirstName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditFirstName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddFirstName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="tbEditLastName" runat="server" Text='<%# Eval("LastName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditLastName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddLastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddLastName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

<div id="SummaryContainer"><asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="BulletList" ShowMessageBox="true" ShowSummary="true" HeaderText="Please correct the following errors:" ValidationGroup="Update" /><asp:ValidationSummary ID="ValidationSummary2" runat="server" DisplayMode="BulletList" ShowMessageBox="true" ShowSummary="true" HeaderText="Please correct the following errors:" ValidationGroup="Add" /></div>

<asp:SqlDataSource ID="dsStudents" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:TriCConnectionString %>" DeleteCommand="DELETE FROM [Student] WHERE [StudentId] = @original_StudentId AND [FirstName] = @original_FirstName AND [LastName] = @original_LastName"
InsertCommand="INSERT INTO [Student] ([StudentId], [FirstName], [LastName]) VALUES (@StudentId, @FirstName, @LastName)"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [Student]"
UpdateCommand="UPDATE [Student] SET [FirstName] = @FirstName, [LastName] = @LastName WHERE [StudentId] = @original_StudentId AND [FirstName] = @original_FirstName AND [LastName] = @original_LastName">
<DeleteParameters>
<asp:Parameter Name="original_StudentId" Type="String" />
<asp:Parameter Name="original_FirstName" Type="String" />
<asp:Parameter Name="original_LastName" Type="String" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="original_StudentId" Type="String" />
<asp:Parameter Name="original_FirstName" Type="String" />
<asp:Parameter Name="original_LastName" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="StudentId" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
</InsertParameters>
</asp:SqlDataSource>

<p class="error"><asp:Label ID="lblError" runat="server"></asp:Label></p>
</div>
</form>
<script type="text/javascript" src="JavaScript2.js"></script>
</body>
</html>


There is a lot of code, so I'll split the code up into 2 posts....see next post for the rest of the code....

chump2877
09-12-2007, 02:50 PM
The rest of the code:

Students.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Week12
{
public partial class Students : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Remove error message, if it exists
lblError.Text = "";
}
protected void gvStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
// Insert new row into database and GridView
string studentId = ((TextBox)gvStudents.FooterRow.FindControl("tbAddStudentId")).Text;
string firstName = ((TextBox)gvStudents.FooterRow.FindControl("tbAddFirstName")).Text;
string lastName = ((TextBox)gvStudents.FooterRow.FindControl("tbAddLastName")).Text;
dsStudents.InsertParameters["StudentId"].DefaultValue = studentId;
dsStudents.InsertParameters["FirstName"].DefaultValue = firstName;
dsStudents.InsertParameters["LastName"].DefaultValue = lastName;
dsStudents.Insert();
gvStudents.DataBind();
}
}
protected void gvStudents_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
// Handle exception during UPDATE query
lblError.Text = "<b>An Error Occurred: </b>" + e.Exception.Message;
e.ExceptionHandled = true;
}
}
protected void gvStudents_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception != null)
{
// Handle exception during DELETE query
lblError.Text = "<b>An Error Occurred: </b>" + e.Exception.Message;
e.ExceptionHandled = true;
}
}
}
}


JavaScript2.js

function attachAllEvents()
{
var inputColl = document.getElementsByTagName("input");
for (var i=0; i<inputColl.length; i++)
{
// If it's a delete button, attach click event
if (inputColl[i].value == "Delete" && inputColl[i].getAttribute("type") == "submit")
attachConfirmDeleteEvent(inputColl[i]);
}

var formObj = document.getElementsByTagName("form")[0];

// If ASP.NET has already created an onsubmit handler, save handler code to a string and remove the handler
if (formObj.getAttribute("onsubmit"))
{
formObj.onSubmitCode = formObj.getAttribute("onsubmit").toString();
formObj.onSubmitCode = formObj.onSubmitCode.replace(/function anonymous\(\)/,"");
formObj.onSubmitCode = formObj.onSubmitCode.replace(/return/,"");
formObj.onSubmitCode = formObj.onSubmitCode.replace(/[\{\}\s]+/g,"");
formObj.onsubmit = null;
}

formObj.onsubmit = function()
{
// If a delete button was clicked...
if (this.blah == 1)
{
// Reset variable blah to something other than 1 so that subsequent clicks of other buttons do not use this conditional code
this.blah = 2;
// This is a delete button, so prompt user to confirm delete
return confirm("Are you sure you want to permanently delete this record?");
}

// If this is not a delete button, and previous onsubmit handler code is saved to a string, evaluate the string as code and return boolean value
if (this.onSubmitCode)
return eval(this.onSubmitCode);
};
}
function attachConfirmDeleteEvent(inputObj)
{
inputObj.onclick = function()
{
// Onclick event fires before onsubmit event, so dynamically add a property to the form that will indicate to the subsequent onsubmit handler that a delete submit button was clicked
this.form.blah = 1;
return true;
};
}
window.onload = function()
{
attachAllEvents();

// Remove validation summary if JS is enabled and use JS alert instead. This code is useless right now, because the GridView control is already too reliant on JS. But in the future, if I decide to customize the Gridview to work without JS as well as with it, then this code will be useful -- so I left the code in for now.
if (document.getElementById('SummaryContainer'))
{
var node = document.getElementById('SummaryContainer');
node.removeChild(node.childNodes[0]);
node.removeChild(node.childNodes[0]);
}
};


OK, that's all of it....props to anyone who can solve this mystery for me....

nikkiH
09-12-2007, 04:32 PM
Why are you using Eval instead of Bind for the edit item templates?

<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Eval("FirstName") %>' MaxLength="50"></asp:TextBox>

<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Bind("FirstName") %>' MaxLength="50"></asp:TextBox>

nikkiH
09-12-2007, 04:35 PM
Eval is one-way binding only. Bind works both ways. I think you need that.

chump2877
09-12-2007, 04:59 PM
Why are you using Eval instead of Bind for the edit item templates?

<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Eval("FirstName") %>' MaxLength="50"></asp:TextBox>

<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Bind("FirstName") %>' MaxLength="50"></asp:TextBox>

Well, I'm not binding the Textbox value to another data source...i'm using the GridView's data source...plus this is just populating the Textbox's text value, so it shouldn;t effect the actual DB transaction...

I'll try this anyway and see if it works, and report back...Thanks.

chump2877
09-12-2007, 05:13 PM
Yay, I did as you said and I've gotten rid of the UPDATE query exception!!....:thumbsup:

Eval is one-way binding only. Bind works both ways. I think you need that.

Can you explain to me why this worked for updating a row...apparently I don;t have a clue, or my understanding of what Bind really means is wrong...what exactly is the difference between one- and two-way binding?

Nevertheless, I'm still getting the same exception when I try to delete a row....We're half way there Nikki !!! Don;t quit on me now...;)

chump2877
09-12-2007, 05:18 PM
Oh, in case you need it, here's the updated source for Students.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Students.aspx.cs" Inherits="Week12.Students" %>
<!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>Student GridView</title>
<link type="text/css" rel="Stylesheet" href="Students.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvStudents" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="StudentId" DataSourceID="dsStudents" ForeColor="#333333" GridLines="None" PageSize="5" ShowFooter="True" OnRowCommand="gvStudents_RowCommand" OnRowDeleted="gvStudents_RowDeleted" OnRowUpdated="gvStudents_RowUpdated">
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnUpdateStudent" runat="server" CommandName="Update" Text="Update" ValidationGroup="Update" />
<asp:Button ID="btnCancelEdit" runat="server" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEditStudent" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="btnDeleteStudent" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddStudent" runat="server" CommandName="Insert" Text="Add Student" ValidationGroup="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="StudentId">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddStudentId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="ID is a required field." ControlToValidate="tbAddStudentId" SetFocusOnError="true" Display="None" ValidationGroup="Add"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="You entered an invalid ID." ControlToValidate="tbAddStudentId" SetFocusOnError="true" ValidationExpression="^[A-Z]{2}\d{4}$" Display="None" ValidationGroup="Add"></asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Bind("FirstName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditFirstName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddFirstName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="tbEditLastName" runat="server" Text='<%# Bind("LastName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditLastName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddLastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddLastName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<EditRowStyle BackColor="#999999" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

<div id="SummaryContainer"><asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="BulletList" ShowMessageBox="true" ShowSummary="true" HeaderText="Please correct the following errors:" ValidationGroup="Update" /><asp:ValidationSummary ID="ValidationSummary2" runat="server" DisplayMode="BulletList" ShowMessageBox="true" ShowSummary="true" HeaderText="Please correct the following errors:" ValidationGroup="Add" /></div>

<asp:SqlDataSource ID="dsStudents" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:TriCConnectionString %>" DeleteCommand="DELETE FROM [Student] WHERE [StudentId] = @original_StudentId AND [FirstName] = @original_FirstName AND [LastName] = @original_LastName"
InsertCommand="INSERT INTO [Student] ([StudentId], [FirstName], [LastName]) VALUES (@StudentId, @FirstName, @LastName)"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [Student]"
UpdateCommand="UPDATE [Student] SET [FirstName] = @FirstName, [LastName] = @LastName WHERE [StudentId] = @original_StudentId AND [FirstName] = @original_FirstName AND [LastName] = @original_LastName">
<DeleteParameters>
<asp:Parameter Name="original_StudentId" Type="String" />
<asp:Parameter Name="original_FirstName" Type="String" />
<asp:Parameter Name="original_LastName" Type="String" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="original_StudentId" Type="String" />
<asp:Parameter Name="original_FirstName" Type="String" />
<asp:Parameter Name="original_LastName" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="StudentId" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
</InsertParameters>
</asp:SqlDataSource>

<p class="error"><asp:Label ID="lblError" runat="server"></asp:Label></p>
</div>
</form>
<script type="text/javascript" src="JavaScript2.js"></script>
</body>
</html>

chump2877
09-12-2007, 05:56 PM
Can you explain to me why this worked for updating a row...apparently I don;t have a clue, or my understanding of what Bind really means is wrong...what exactly is the difference between one- and two-way binding?


Answered my own question with VS2005 help index:


In ASP.NET, data-bound controls such as the GridView, DetailsView, and FormView controls can automatically use the update, delete, and insert operations of a data source control. For example, if you have defined SQL Select, Insert, Delete, and Update statements for your data source control, using Bind in a GridView, DetailsView, or FormView control template enables the control to extract values from child controls in the template and pass them to the data source control. The data source control in turn performs the appropriate command for the database. For this reason, the Bind function is used inside the EditItemTemplate or InsertItemTemplate of a data-bound control.


Still need help with the DELETE query exception though...thanks!!

nikkiH
09-12-2007, 08:35 PM
Sorry, i got caught up in something here at work. :D

Is this current?
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
change that to bind as well.

nikkiH
09-12-2007, 08:38 PM
Sorry, i got caught up in something here at work. :D

Is this current?
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
change that to bind as well.

This thing never wants to let me edit. LOL

Anyway, this is what I meant to post:

Sorry, i got caught up in something here at work. :D

Is this current?
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>

Student ID will need to be a databound control or it won't find it for original_id; I don't think you can databind a label. You may need to borrow a different type to duplicate it where the user cannot see it but the engine can, such as a hidden control.

chump2877
09-13-2007, 12:05 AM
Is this current?
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>

Student ID will need to be a databound control or it won't find it for original_id; I don't think you can databind a label. You may need to borrow a different type to duplicate it where the user cannot see it but the engine can, such as a hidden control.


Well the logic makes sense...So I tried this:

<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("StudentId") %>' />
</ItemTemplate>

and this:

<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("StudentId") %>' Visible="false" ReadOnly="true"></asp:TextBox>
</ItemTemplate>

and even this:

<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("StudentId") %>'></asp:Label>
</ItemTemplate>

No dice....none of them worked -- I still get the exception thrown when trying to delete a row...

Any ideas? I feel like you're on to something here...;)

Thanks.

chump2877
09-13-2007, 12:53 AM
Well, i got the exceptions to go away....This is the relevant code that I changed:


<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="btnUpdateStudent" runat="server" CommandName="Update" Text="Update" ValidationGroup="Update" />
<asp:Button ID="btnCancelEdit" runat="server" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnEditStudent" runat="server" CommandName="Edit" Text="Edit" />
<asp:Button ID="btnDeleteStudent" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddStudent" runat="server" CommandName="Insert" Text="Add Student" ValidationGroup="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="StudentId">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentId") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddStudentId" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="ID is a required field." ControlToValidate="tbAddStudentId" SetFocusOnError="true" Display="None" ValidationGroup="Add"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="You entered an invalid ID." ControlToValidate="tbAddStudentId" SetFocusOnError="true" ValidationExpression="^[A-Z]{2}\d{4}$" Display="None" ValidationGroup="Add"></asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="tbEditFirstName" runat="server" Text='<%# Bind("FirstName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditFirstName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="First Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddFirstName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="tbEditLastName" runat="server" Text='<%# Bind("LastName") %>' MaxLength="50"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbEditLastName" ValidationGroup="Update"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbAddLastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Last Name is a required field." Display="None" SetFocusOnError="true" ControlToValidate="tbAddLastName" ValidationGroup="Add"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
</Columns>


Ultimately, it had to do with which controls used Eval and which used Bind...Apparently, controls that display primary key values don't need to use (and shouldn't use) Bind (because primary key values shouldn;t change during these DB operations), whereas ItemTemplate controls need to use Bind for the Delete row function to work, and EditItemTemplate controls need to use Bind for the Update row function to work....That sound right to you?

Anyway, thanks for your help with this and getting me on the right track!! Much appreciated...:thumbsup:

nikkiH
09-13-2007, 03:18 PM
Glad to help :)