最近用到GridView自带的编辑、更新、删除、取消按钮,研究了一番其中包括绑定gridview数据、编辑行内数据、删除数据、根据条件隐藏显示编辑删除或自定义按钮,把代码共享一下,帮助有需要的人:
效果图1(根据审核未审核显示编辑删除按钮):
效果图2:(审核后隐藏编辑删除按钮)
前台代码:
<asp:GridView ID="GVData" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
BorderStyle="Solid" BorderWidth="1px" OnRowDataBound="GVData_RowDataBound" PageSize="15"
Width="100%" OnRowCancelingEdit="GVData_RowCancelingEdit" OnRowEditing="GVData_RowEditing" OnRowUpdating="GVData_RowUpdating" OnRowDeleting="GVData_RowDeleting">
<PagerSettings Mode="NumericFirstLast" Visible="False" />
<PagerStyle BackColor="LightSteelBlue" HorizontalAlign="Right" />
<HeaderStyle BackColor="#464646" Font-Size="14px" ForeColor="White" Height="30px" />
<AlternatingRowStyle BackColor="#EAEAEA" />
<Columns>
<asp:TemplateField HeaderText="序号">
<ItemTemplate>
<%# Container.DataItemIndex + 1%>
</ItemTemplate>
<ControlStyle Width="35px"></ControlStyle>
<ItemStyle Width="35px" />
</asp:TemplateField>
<asp:BoundField DataField="库单商品序号" HeaderText="库单商品序号" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="产品名称" HeaderText="产品名称" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="入库数量" HeaderText="数量"></asp:BoundField>
<asp:BoundField DataField="单价" HeaderText="单价" ></asp:BoundField>
<asp:TemplateField HeaderText="金额">
<ItemTemplate>
<%# !String.IsNullOrEmpty(DataBinder.Eval(Container.DataItem, "单价").ToString()) ? DataBinder.Eval(Container.DataItem, "单价").ToString():"未填写单价"%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="金额">
<ItemTemplate>
<%#(!String.IsNullOrEmpty(Eval("入库数量").ToString())&&!String.IsNullOrEmpty(Eval("单价").ToString()))?(decimal.Parse(Eval("入库数量").ToString()) * decimal.Parse(Eval("单价").ToString())).ToString():"0"%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="供应商" HeaderText="供应商" ReadOnly="true"></asp:BoundField>
<asp:BoundField DataField="经办人" HeaderText="采购人" ReadOnly="true"></asp:BoundField>
<asp:TemplateField HeaderText="状态">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "状态").ToString() == "0" ? "已提交未审核" : (DataBinder.Eval(Container.DataItem, "状态").ToString() == "1" ? "已审核" : "未通过")%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="创建时间" HeaderText="创建时间" ReadOnly="true"></asp:BoundField>
<asp:CommandField HeaderText="编辑" ShowEditButton="true" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<RowStyle HorizontalAlign="Center" Height="35px" />
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="center" style="border-right: black 1px; border-top: black 1px; border-left: black 1px;
border-bottom: black 1px; background-color: whitesmoke;">
该列表中暂时无数据!
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
后台代码:
ps:编辑、删除按钮不要通过属性去显示,手动设置显示
<asp:CommandField HeaderText="编辑" ShowEditButton="true" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
//绑定数据源
public void DataBindToGridview()
{
MiroSoft.BLL.库单商品表 oper = new MiroSoft.BLL.库单商品表();
if (Request.QueryString["id"] != null)
{
List<MiroSoft.Model.库单商品表> list = new List<MiroSoft.Model.库单商品表>();
//这里将数据库查询出的数据转换成了list集合 便于下边循环判断条件去显示隐藏按钮
//dataset转换为list集合可查看最后一个方法
list = oper.getlistkudanshangpinbiao("单具序号=" + Request.QueryString["id"].ToString());
GVData.DataSource = list;
GVData.DataBind();
if (Request.QueryString["status"] != "")
{
for (int i = 0; i < this.GVData.Rows.Count; i++)
{
//获取删除按钮 意思是获取gridview第12列第一个控件
LinkButton delete = GVData.Rows[i].Cells[12].Controls[0] as LinkButton;
LinkButton edit = GVData.Rows[i].Cells[11].Controls[0] as LinkButton;
//获取按钮 意思是获取第i行的 lblStatus 控件 前台代码<asp:Label ID="lblStatus" runat="server" Enabled="false"></asp:Label>
//Label lblStatus = this.grvApplyInfo.Rows[i].FindControl("lblStatus") as Label;
//根据条件去选择隐藏还是显示
if (list[i].状态.Value.ToString().Trim() == "1"|| list[i].状态.Value.ToString().Trim() == "2")
{
edit.Visible=false;
delete.Visible = false;
}
else
{
edit.Visible = true;
delete.Visible = true;
}
}
}
}
else
{
List<MiroSoft.Model.库单商品表> list = new List<MiroSoft.Model.库单商品表>();
list = oper.getlistkudanshangpinbiao("");
GVData.DataSource = list;
GVData.DataBind();
//传过来的状态如果不为空
if (Request.QueryString["status"] == "0")
{
for (int i = 0; i < this.GVData.Rows.Count; i++)
{
//获取删除按钮 意思是获取gridview第12列第一个控件
LinkButton lb = GVData.Rows[i].Cells[12].Controls[0] as LinkButton;
//获取按钮 意思是获取第i行的 lblStatus 控件 前台代码<asp:Label ID="lblStatus" runat="server" Enabled="false"></asp:Label>
//Label lblStatus = this.grvApplyInfo.Rows[i].FindControl("lblStatus") as Label;
//根据条件去选择隐藏还是显示
if (list[i].状态.Value.ToString().Trim() == "1" || list[i].状态.Value.ToString().Trim() == "2")
{
lb.Visible = false;
}
else
{
lb.Visible = true;
}
}
}
}
LabPageSum.Text = Convert.ToString(GVData.PageCount);
LabCurrentPage.Text = Convert.ToString(((int)GVData.PageIndex + 1));
this.GoPage.Text = LabCurrentPage.Text.ToString();
}
//编辑
protected void GVData_RowEditing(object sender, GridViewEditEventArgs e)
{
GVData.EditIndex = e.NewEditIndex;
DataBindToGridview();
}
//更新
protected void GVData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//string id = ((TextBox)GVData.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString().Trim();
string id = GVData.Rows[e.RowIndex].Cells[1].Text.ToString();
string num = ((TextBox)(GVData.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim();//数量 //强制转换 获取第四列第一个控件的值
string money = ((TextBox)GVData.Rows[e.RowIndex].Cells[4].Controls[0]).Text.Trim();//单价 //强制转换
MiroSoft.BLL.库单商品表 oper = new MiroSoft.BLL.库单商品表();
int aa = oper.getresoult(id, num, money);
if (aa > 0)
{
this.GVData.EditIndex = -1;
DataBindToGridview();
}
else
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('修改失败!');</script>");
}
}
//取消
protected void GVData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GVData.EditIndex = -1;
DataBindToGridview();
}
//删除
protected void GVData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GVData.Rows[e.RowIndex].Cells[1].Text.ToString();//获取库单商品序号
MiroSoft.BLL.库单商品表 oper = new MiroSoft.BLL.库单商品表();
int aa = oper.getdelresoult(id);
if (aa > 0)
{
GVData.DataBind();
DataBindToGridview();
}
else
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('删除失败!');</script>");
}
}
//删除时弹出提示框
protected void GVData_RowDataBound(object sender, GridViewRowEventArgs e)
{
//ZWL.Common.PublicMethod.GridViewRowDataBound(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[12].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[2].Text + "\"吗?')");
}
}
}
//将DataSet转化为list集合
public List<Model.库单商品表> getlistkudanshangpinbiao(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select 库单商品序号,单具序号,产品序号,产品名称,仓库序号,入库数量,单价,供应商,经办人,创建时间,更新时间,状态,备注 ");
strSql.Append(" FROM 库单商品表 ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
DataTable dt= DbHelperSQL.Query(strSql.ToString()).Tables[0];
//转换成集合要有一个model类包含数据库所有的字段
List<Model.库单商品表> list = new List<Model.库单商品表>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Model.库单商品表 app = new Model.库单商品表
{
库单商品序号 = Convert.ToInt32(dt.Rows[i]["库单商品序号"]),
单具序号 = Convert.ToInt32(dt.Rows[i]["单具序号"]),
产品序号 = Convert.ToInt32(dt.Rows[i]["产品序号"]),
产品名称 = dt.Rows[i]["产品名称"].ToString(),
仓库序号 = Convert.ToInt32(dt.Rows[i]["仓库序号"]),
入库数量 = Convert.ToDecimal(dt.Rows[i]["入库数量"]),
单价 = Convert.ToDecimal(dt.Rows[i]["单价"]),
供应商 = dt.Rows[i]["供应商"].ToString(),
经办人 = dt.Rows[i]["经办人"].ToString(),
创建时间 = Convert.ToDateTime(dt.Rows[i]["创建时间"]),
更新时间 = Convert.ToDateTime(dt.Rows[i]["更新时间"]),
状态 = Convert.ToInt32(dt.Rows[i]["状态"]),
};
//返回的数据如果不确定是否有值 加以判断
if (!DBNull.Value.Equals(dt.Rows[i]["备注"]))
{
app.备注 = dt.Rows[i]["备注"].ToString();
}
list.Add(app);//添加到集合
}
return list;
}