我无法使用ASP和C#返回列表视图并取消项目编辑。
我已经和this有了相同的答案
但我仍然收到Cancel can only be called from the currently-edited record or an insert item.
这是有问题的代码 - 任何关于导致这种情况的指针都非常有用:
我还有一个布局,选定的模板和插入,它们都是相同的。
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqlDatasource1"
EnableViewState="true" DataKeyNames="EndUserId" AllowPaging="True"
OnItemCommand="ListView1_ItemCommand" OnItemCanceling="ListView1_ItemCanceling">
<EditItemTemplate>
<tr>
<asp:Label runat="server" ID="tbId" Text='<%#Eval("EndUserId") %>' Visible="false" />
<td>
<asp:TextBox runat="server" ID="tbEmail" Text='<%#Eval("Email") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="tbRole" Text='<%#Eval("Role") %>' />
</td>
<td>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
c#后端控制
protected void ListView1_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
ListView1.EditIndex = -1;
ListView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
if (!IsPostBack)
{
}
}
添加了后端
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
Label tbId = (Label)e.Item.FindControl("tbId");
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string updateCommand =
"UPDATE [EndUser_tbl] SET [Email]='" +
tbEmail.Text + "', [Password]='" + tbPass.Text +
"'WHERE EndUserId=" + Convert.ToInt32(tbId.Text) + ";";
sqlDatasource1.UpdateCommand = updateCommand;
}
if (e.CommandName == "Delete")
{
Label id = (Label)e.Item.FindControl("tbId");
string deleteCommand = "DELETE FROM [EndUser_tbl] " +
"WHERE EndUserId=" + Convert.ToInt32(id.Text);
sqlDatasource1.DeleteCommand = deleteCommand;
}
if (e.CommandName == "Insert")
{
TextBox tbEmail = (TextBox)e.Item.FindControl("tbEmail");
TextBox tbPass = (TextBox)e.Item.FindControl("tbPass");
string insertCommand = "INSERT INTO [EndUser_tbl] " +
"([Email],[Password],[ContractRef],[Role])" +
"VALUES ('" + tbEmail.Text + "','" + tbPass.Text +
"','" + tbPass.Text + "');";
sqlDatasource1.InsertCommand = insertCommand;
}
}
答案 0 :(得分:1)
像这样改变Page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListView1.EditIndex = -1;
ListView1.InsertItemPosition = InsertItemPosition.LastItem;
}
}
再试一次。