。net学习基础之gridView的使用
1.绑定
前台:
<asp:GridView ID="gvUpdateGift" runat="server" Height="146px" Width="500px" AutoGenerateColumns="False" DataKeyNames="编号" OnRowCommand="gvUpdateGift_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table style="width: 100%">
<tr>
<td style="width: 150px; height: 21px;">
<asp:TextBox ID="txtName" runat="server" BorderStyle="Groove" Text='<%# Eval("名称") %>'
Width="131px"></asp:TextBox></td>
<td style="width: 30px; height: 21px;">
<asp:TextBox ID="txtLevels" runat="server" BorderStyle="Groove" Text='<%# Eval("级别") %>'
Width="30px"></asp:TextBox></td>
<td style="width: 110px; height: 21px;">
<asp:TextBox ID="txtStart" runat="server" BorderStyle="Groove" Text='<%# Eval("开始时间") %>'
Width="93px"></asp:TextBox></td>
<td style="width: 110px; height: 21px;">
<asp:TextBox ID="txtEnd" runat="server" BorderStyle="Groove" Text='<%# Eval("结束时间") %>'
Width="93px"></asp:TextBox></td>
<td style="width: 50px; height: 21px">
<asp:LinkButton ID="lbtnEdit" runat="server" BorderStyle="Groove" CommandName="select" CommandArgument='<%# Eval("编号") %>' Text="选择" />
</td>
<td style="width: 50px; height: 21px">
<asp: LinkButton ID="lbtnDelete" runat="server" BorderStyle="Groove" CommandName="delete" CommandArgument='<%# Eval("编号") %>' Text="删除" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
后台:
protected void gvUpdateGift_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "delete")//删除
{
GiftOp objgiftop = new GiftOp();
int gid = int.Parse(e.CommandArgument.ToString());
objgiftop.Delete(gid);
Bind();
}
}
重点:触发按钮的CommandArgument属性
------------------------------------------------------------------------
2.gv的手动绑定与更新删除
protected void gvLeavewordManage_RowDeleting(object sender, GridViewDeleteEventArgs e)//获得键值再行删除
{
ClassLeaveword objLeaveword = new ClassLeaveword();
int leavewordid = int.Parse(this.gvLeavewordManage.DataKeys[e.RowIndex].Value.ToString());
try
{
objLeaveword.DeleteLeaveword(leavewordid);
}
catch (Exception err)
{
throw err;
}
}
3.获得gv触发事件的行
GridViewRow row = ((Control)e.CommandSource).BindingContainer as GridViewRow;//获得当前行的值
int index = row.RowIndex;
int packageid = int.Parse(e.CommandArgument.ToString());
Label lbl = row.FindControl("lblPname") as Label;
this.lblNamed.Text = lbl.Text;
TextBox txt = row.FindControl("txtPprice") as TextBox;
this.txtChangPrice.Text = txt.Text;
----------------------------------------------------------
------------------------------------------------------------------------------------------------------------
3.gv的分页:
--------------------------前台:----------------------------------
<table style="vertical-align:top;border-right: #ff3300 1px solid; border-top: #ff3300 1px solid; border-left: #ff3300 1px solid;
width: 245px; border-bottom: #ff3300 1px solid;width: 100%">
<tr>
<td style="background-image: url(Images/bg_Class/table_bg.gif); background-repeat: repeat-x; height: 19px; width: 494px;">
<span style="font-size:
</tr>
<tr>
<td style="width: 494px; height: 19px;">
<span style="font-size:
ID="lbtnDefault" runat="server" ForeColor="Blue" CommandArgument="套餐" OnClick="lbtnClick">默认分类</asp:LinkButton>·<asp:LinkButton
ID="lbtnMain" runat="server" ForeColor="Blue" CommandArgument="汉堡" OnClick="lbtnClick">特色主食</asp:LinkButton>·<asp:LinkButton
ID="lbtnDrink" runat="server" ForeColor="Blue" CommandArgument="饮料" OnClick="lbtnClick">甜品饮料</asp:LinkButton>·<asp:LinkButton
ID="lbtnNosh" runat="server" ForeColor="Blue" CommandArgument="小吃" OnClick="lbtnClick">可口小吃</asp:LinkButton>·<asp:LinkButton
ID="lbtnPackage" runat="server" ForeColor="Blue" CommandArgument="套餐" OnClick="lbtnClick">套餐系列</asp:LinkButton></span></td>
</tr>
<tr>
<td style="width: 494px; height: 21px; text-align: center;">
<asp:GridView ID="gvBycategory" runat="server" AutoGenerateColumns="False" DataKeyNames="编号" PageSize="2"
Width="425px" ShowHeader="False" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<table style="border-right: #ff3300 1px solid; border-top: #ff3300 1px solid; border-left: #ff3300 1px solid;
width: 434px; border-bottom: #ff3300 1px solid; height: 95px">
<tr>
<td rowspan="3" style="border-left-color: #ff3300; border-bottom-color: #ff3300;
width: 60px; border-top-color: #ff3300; border-right-color: #ff3300">
<asp:Image ID="Image1" runat="server" Height="88px" ImageUrl='<%# Eval("图片地址") %>'
Width="119px" /></td>
<td style="width: 119px; height: 28px">
<span style="font-size:
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Eval("编号") %>'
CommandName="Buy" ForeColor="Blue" Text='<%# Eval("名称") %>' Width="118px"></asp:LinkButton></span></td>
</tr>
<tr>
<td style="width: 119px">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("价格") %>' Width="139px"></asp:Label></td>
</tr>
<tr>
<td style="width: 119px">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("描述") %>' Width="138px"></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="lnkFirst" runat="server" CommandName="first" OnCommand="Btn_Click" ForeColor="Blue" Enabled="False">首页</asp:LinkButton>
<asp:LinkButton ID="lnkPrevious" runat="server" ForeColor="Blue" OnCommand="Btn_Click" CommandName="before" Enabled="False">上一页</asp:LinkButton>
<asp:LinkButton ID="lnkNext" runat="server" ForeColor="Blue" OnCommand="Btn_Click" CommandName="next" Enabled="False">下一页</asp:LinkButton>
<asp:LinkButton ID="lnkEnd" runat="server" Width="37px" OnCommand="Btn_Click" CommandName="end" ForeColor="Blue" Enabled="False">末页</asp:LinkButton>
第<asp:Label ID="lblNowPage" runat="server" Text="0" Width="2px"></asp:Label>
/<asp:Label ID="lblTotalPage" runat="server" Text="0" Width="2px"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="0" >页</asp:Label>
</td>
</tr>
</table>
--------------------------后台:----------------------------------
protected void Page_Load(object sender, EventArgs e)
{
}
protected void lbtnClick(object sender, EventArgs e)//按分类查看商品
{
Session["pagesize"] = 2;
int pagesize = 2;
int totalpage = 0;
LinkButton lbtnTmp = sender as LinkButton;
ProductOp objproductop = new ProductOp();
DataTable dt = objproductop.SelectByCategory(lbtnTmp.CommandArgument);
if (dt.Rows.Count % pagesize!=0)
{
totalpage = dt.Rows.Count / pagesize +1;
}
else
{
totalpage = dt.Rows.Count / pagesize;
}
lblTotalPage.Text = totalpage.ToString();
//this.gvBycategory.PageIndex = 1;
Session["totalpage"] = totalpage;
Session["nowpage"] = 1;
Session["categroyname"]=lbtnTmp.CommandArgument;//放入分类名
GvBind();
}
public void GvBind()//绑定某页(页数从1开始)
{
//手写绑定第 nowpage*pagesize+1 到 (nowpage+1)*pagesize 项
string categroyname = "套餐";
int pagesize=int.Parse(Session["pagesize"].ToString());
int nowpage=int.Parse(Session["nowpage"].ToString());
lblNowPage.Text = nowpage.ToString();
if (null != Session["categroyname"])
{
categroyname = Session["categroyname"].ToString();
}
ProductOp objproductop = new ProductOp();
DataTable dt = objproductop.SelectByCategory(categroyname, pagesize, nowpage-1);
this.gvBycategory.DataSource = dt;
this.gvBycategory.DataBind();
LblDisplay();
}
/// <summary>
/// 分页操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Btn_Click(Object sender, CommandEventArgs e)
{
int nowpage = int.Parse(Session["nowpage"].ToString());
int totalpage = int.Parse(Session["totalpage"].ToString());
switch (e.CommandName)
{
case "first":
Session["nowpage"] = 1;
GvBind();
break;
case "next":
Session["nowpage"] = nowpage + 1;
GvBind();
break;
case "before":
Session["nowpage"] = nowpage - 1;
GvBind();
break;
case "end":
Session["nowpage"] = totalpage;
GvBind();
break;
default:
break;
}
}
public void LblDisplay()//按钮的可用情况
{
int nowpage = int.Parse(Session["nowpage"].ToString());
int totalpage = int.Parse(Session["totalpage"].ToString());
if (nowpage == 1)//是否只有一页
{
this.lnkFirst.Enabled = false;
this.lnkPrevious.Enabled = false;
if (totalpage > 1)
{
this.lnkNext.Enabled = true;
this.lnkEnd.Enabled = true;
}
else
{
this.lnkNext.Enabled = false;
this.lnkEnd.Enabled = false;
}
}
else if (nowpage == totalpage)//最后一页
{
this.lnkNext.Enabled = false;
this.lnkEnd.Enabled = false;
if (totalpage >= 1)//仅一页
{
this.lnkFirst.Enabled = true;
this.lnkPrevious.Enabled = true;
}
else
{
this.lnkFirst.Enabled = false;
this.lnkPrevious.Enabled = false;
}
}
else if (nowpage != 1 || nowpage != totalpage)
{
this.lnkNext.Enabled = true;
this.lnkEnd.Enabled = true;
this.lnkFirst.Enabled = true;
this.lnkPrevious.Enabled = true;
}
}
------------------------------------------------------------
.自带AJAX的gv分页:
------------------------------------------------------------
前台:
AutoGenerateColumns="true"即允许动态生成页内容
EnableSortingAndPagingCallbacks="true"表示允许异步提交页码
-----------------------------------------------------------
<asp:GridView runat="server" ID="gvPaging"
AllowPaging="true"
PageSize="10"
AutoGenerateColumns="true"
Width="200"
EnableSortingAndPagingCallbacks="true"
/>
-----------------------------------------------------------
后台:
-----------------------------------------------------------
private static DataTable dt = null;//在page_load()上定义
//在page_load中制作了一个(n行2列)表,并绑定
//实质上后台就只是一个绑定
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
for (int i = 0; i < 100; i++)
{
dt.Rows.Add(new object[] { i + 1, "Name " + (i + 1) });
}
}
this.gvPaging.DataSource = dt;
this.gvPaging.DataBind();
-----------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
4.gv的嵌套(使用见项目实现):
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
5.gv的模板:
(1).响应DataList、Repeater 和GridView 控件中的按钮事件
.见DataList篇.
(2).为 GridView 控件创建模板列
.首先编辑列(添加n个模板列TemplateField)
.再编辑模板ItemTemplate中的各个模板列
如有按钮等要设计CommandName属性与gv的RowCommand事件以及if判断(见下3)
.最后(实为第一步)连接数据库
(3).获得模板中所选行的列值(可直接用)
---------------前台----------------
<div>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" DataKeyNames="pid"
DataSourceID="SqlDataSource1" OnRowCommand="GridView3_RowCommand">
<Columns>
<asp:TemplateField HeaderText="pid">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("pid") %>' Width="132px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="pname">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("pname") %>' Width="132px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="pspecs">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("pspecs") %>' Width="132px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="psprice">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("psprice") %>' Width="88px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="选择">
<ItemTemplate>
<asp:Button CommandName="Display" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"pname")%>' ID="Buy" runat="server" Text="显示产品名" Width="111px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Top" />
</asp:GridView><span style="color: #ff0000">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SaleSymConnectionString9 %>"
SelectCommand="SELECT * FROM [Product]"></asp:SqlDataSource>
<br />
<br />
您选择的产品名为:
<asp:Label ID="lblMsg" runat="server" ForeColor="Red" Text="Label" Width="132px"></asp:Label><br />
</div>
---------------后台----------------
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "Display")
{
this.lblMsg.Text = e.CommandArgument.ToString();
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
6.绑定XML
protected void Page_Load(object sender, EventArgs e)//绑定XML文件
{
//string path = "C:\\Documents and Settings\\Administrator\\桌面\\test\\App_Data\\Class.XML";
string FilePath = MapPath("App_Data\\Class.XML");//
DataSet ds = new DataSet();
//ds.ReadXml(path);
ds.ReadXml(FilePath);
GridView2.DataSource = ds.Tables[0].DefaultView;
GridView2.DataBind();
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
7.获得gv中某行某列
for (int i = 0; i < this.GridView1.Rows.Count; i++)
{
if (null != this.GridView1.Rows[i].Cells[0].FindControl("label5"))
{
Label lblTmp = ((Label)this.GridView1.Rows[i].Cells[0].FindControl("label5"));
if (lblTmp.Text == "True")
{
lblTmp.Text = "男";
}
else
{
lblTmp.Text = "女";
}
}
}
------------------------------
按id寻找母控件中的子控件:FindControl("label5")
--
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
8.gv的行变色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor='White';this.style.color='#000000'");
e.Row.Attributes.Add("OnMouseOver", "this.style.backgroundColor='#FFEFD5';this.style.color='#
//双击事件
e.Row.Attributes.Add("OnDblClick", "DbClickEvent('" + e.Row.Cells[1].Text + "','" + e.Row.Cells[0].Text + "')");
//单击事件
//e.Row.Attributes.Add("OnClick", "ClickEvent('" + e.Row.Cells[1].Text + "')");
//按钮按下事件
//e.Row.Attributes.Add("OnKeyDown", "GridViewItemKeyDownEvent('" + e.Row.Cells[1].Text + "')");
e.Row.Attributes["style"] = "Cursor:hand";
}
}
9.gv的传参+绑定obj
---------------------(1).前台-----------------
<asp:GridView ID="gvTop5" runat="server" AutoGenerateColumns="False" PageSize="5" DataSourceID="ObjectDataSourceTop" Width="324px" DataKeyNames="productid" OnRowCommand="gvTop5_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table style="border-right: #ff3300 1px solid; border-top: #ff3300 1px solid; border-left: #ff3300 1px solid;
width: 331px; border-bottom: #ff3300 1px solid; height: 95px">
<tr>
<td rowspan="3" style="border-left-color: #ff3300; border-bottom-color: #ff3300;
width: 90px; border-top-color: #ff3300; border-right-color: #ff3300">
<asp:Image ID="Image1" runat="server" Height="88px" ImageUrl='<%# Eval("ImageUrl") %>'
Width="119px" /></td>
<td style="width: 119px; height: 28px;">
<span style="font-size:
<asp:LinkButton ID="LinkButton1" runat="server"
Text='<%# Eval("productName") %>' Width="118px" ForeColor="Blue" CommandArgument='<%# Eval("productid") %>' CommandName="Buy"></asp:LinkButton></td>
</tr>
<tr>
<td style="width: 119px">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("price") %>' Width="139px"></asp:Label></td>
</tr>
<tr>
<td style="width: 119px">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Descriptions") %>' Width="138px"></asp:Label></td>
</tr>
</table>
</ItemTemplate>
<HeaderTemplate>
<span style="color: #ff6600"><strong>本月畅销产品</strong></span>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
---------------------(2)后台--------------------------
protected void gvTop5_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Buy")
{
if (User.Identity.Name == "")//没有登录
{
Response.Write("<script>alert('只有注册成为会员才可以使用购物车,</br>请到前台咨询,谢谢!')</script>");
}
else//已经登录,可以使用购物车
{
int pid = int.Parse(e.CommandArgument.ToString());
}
}
}
------------------(3).注释-----------------------
1.设定gv的绑定
2.设定linkbtn 的CommandArgument='<%# Eval("productid") %>' CommandName="Buy"
其中前者用于传参,后台引用为:e.CommandArgument.ToString()
后者为gv中触发事件的名称
综合操作
-----------=------------------------
<%@ Page Language="C#" MasterPageFile="~/Financer/FinancerMasterPage.master" AutoEventWireup="true" CodeFile="FinancerAnswer.aspx.cs" Inherits="Financer_FinancerAnswer" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2 class="h2_4 bg
<h2 class="h2_
<div class="cls"></div>
<asp:GridView ID="QuestionGrid" runat="server" AutoGenerateColumns="False" Width="100%" AllowPaging="True" PageSize="4" OnPageIndexChanging="QuestionGrid_PageIndexChanging" GridLines="None" DataKeyNames="ReplyID" OnRowDataBound="QuestionGrid_RowDataBound" OnRowDeleting="QuestionGrid_RowDeleting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table width="98%" border="0" cellspacing="0" cellpadding="0" class="t_11">
<tr>
<td colspan="2" class="fontB"><em>所问问题:</em><%# DataBinder.Eval(Container.DataItem, "MQ_Title")%></td>
</tr>
<tr>
<td colspan="2"><%# DataBinder.Eval(Container.DataItem, "Reply_Content")%></td>
</tr>
<tr>
<td align="right"><%# DataBinder.Eval(Container.DataItem, "Addtime")%></td>
<td align="right"> </td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="ReplyID" DataNavigateUrlFormatString="EditFinancerAnswer.aspx?RepID={0}"
Text="编辑">
<ItemStyle Width="30px" />
</asp:HyperLinkField>
<asp:CommandField ShowDeleteButton="True" DeleteText="删除">
<ItemStyle Width="30px"/>
</asp:CommandField>
</Columns>
</asp:GridView>
</asp:Content>
-=-------------------------------------------------------------
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;
public partial class Financer_FinancerAnswer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IfSessionLose.CheckSession("FinancerInfo", "../FinancerLogin.aspx");
if (!IsPostBack)
{
GridViewBind();
}
}
void GridViewBind()
{
if (Session["FinancerInfo"] != null)
{
Hashtable Fin = new Hashtable();
Fin = (Hashtable)Session["FinancerInfo"];
TempDB db = new TempDB();
DataSet ds = new DataSet();
ds = db.getDateSet("SELECT Mem_Question.MQ_Title, Mem_Question_Reply.IsGoodKey,Mem_Question_Reply.Question_ID, Mem_Question_Reply.Addtime,Mem_Question_Reply.Reply_Content, Mem_Question_Reply.ReplyID FROM Mem_Question_Reply INNER JOIN Mem_Question ON Mem_Question_Reply.Question_ID = Mem_Question.MQ_ID WHERE (Mem_Question_Reply.ReplyType = '2') AND Mem_Question_Reply.replyer = '" + Fin["FinID"].ToString() + "'");
QuestionGrid.DataSource = ds.Tables[0];
QuestionGrid.DataBind();
}
}
protected void QuestionGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[2].Controls[0]).Attributes.Add("OnClick", "javascript:return confirm('你确认要删除吗?')");
}
}
}
protected void QuestionGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = QuestionGrid.DataKeys[e.RowIndex].Value.ToString();
OperStat OS = new OperStat();
if (OS.Stat("Select IsGoodKey from Mem_Question_Reply where ReplyID='" + id + "'").Equals("0"))
{
DBOper db = new DBOper();
db.OpenConnection();
db.ExecuteSql("delete Mem_Question_Reply where ReplyID='" + id + "'");
db.CloseConnection();
GridViewBind();
}
else
{
Jscript.AlertAndRedirect("此问题不允许删除", Request.Url.ToString());
}
}
protected void QuestionGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
QuestionGrid.PageIndex = e.NewPageIndex;
GridViewBind();
}
}