您的位置:首页 > 其它

GridView中的编辑和删除按钮获取当前行的非主键字段的值

2009-08-13 14:09 423 查看
GridView控件绑定了一个Flag字段,值如下:0-未审核,1-审核通过,2-审核未通过,数据库中保存的是编号,而GridView中显示的是对应的名称。
要在编辑或删除前需要获取Flag编号,则有两种情况:(在RowDataBound事件中使用DataBinder.Eval(e.Row.DataItem, "Flag").ToString();获取)
(1)如果GridView在显示中未进行转换,直接显示编号,则在编辑或删除时要获取编号值,很简单
在RowDeleting事件中使用GridView.Rows[e.RowIndex].Cells
.Text
在RowEditing事件中使用GridView.Rows[e.NewEditIndex].Cells
.Text
(2)如果GridView在显示时进行了转换,显示的不是编号而是对应的汉字,如果还想在编辑或删除时获取编号,此编号又不是主键,可以通过给编辑或删除按钮设置CommandArgument来实现。
HTML中:

<asp:TemplateField HeaderText="编辑">
<EditItemTemplate>
<asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="Update">更新</asp:LinkButton>
<asp:LinkButton ID="lbtnCancel" runat="server" CausesValidation="False" CommandName="Cancel">取消</asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Flag") %>'
ImageUrl="~/Images/edit.gif" CommandName="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="删除">
<ItemTemplate>
<asp:ImageButton ID="lbtnDelete" runat="server" CausesValidation="False" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Flag") %>'
ImageUrl="~/Images/delete.gif" OnClientClick="return confirm('确定要删除吗?')" />
</ItemTemplate>
</asp:TemplateField>C#中:

protected void gvReward_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string strFlag = ((ImageButton)gvReward.Rows[e.RowIndex].FindControl("lbtnDelete")).CommandArgument;//在HTML中设置了CommandArgument,使其绑定了Falg字段的值
//string strFlag = gvReward.Rows[e.RowIndex].Cells[7].Text.ToString().Trim();//获取当前行中被绑定的‘Flag’字段的值
if (strFlag == "1")
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "", "alert('此信息学工处已审核通过,不允许删除')", true);
}
else
{
int iID = Convert.ToInt32(gvReward.DataKeys[e.RowIndex].Value);
try
{
if (StudentReward.RemoveRewardList(iID))
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "", "alert('删除成功')", true);
BindGridView();
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "", "alert('删除失败')", true);
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "", "alert('删除出现异常')", true);
}
}
}
protected void gvReward_RowEditing(object sender, GridViewEditEventArgs e)
{
string strFlag = ((ImageButton)gvReward.Rows[e.NewEditIndex].FindControl("ImageButton1")).CommandArgument;//在HTML中设置了CommandArgument,使其绑定了Falg字段的值
if (strFlag == "1") //审核没通过的,也可以修改,不过此时审核状态需要同时修改为“0”未审核
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "", "alert('此信息学工处已审核通过,不允许修改')", true);
}
else
{
gvReward.EditIndex = e.NewEditIndex;
BindGridView();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐