Gridview常用技巧
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1.gridview行绑定删除事件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int i;
//执行循环,保证每条数据都可以更新
for (i = 0; i < GridView1.Rows.Count; i++)
{
//首先判断是否是数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#dee9f9'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[8].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除: \"" + e.Row.Cells[5].Text + "\" 的 \""+ e.Row.Cells[1].Text +"\" 的等级考试报名吗?')");
}
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["strcon"]);
con.Open();
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
SqlCommand scd = new SqlCommand("delete from ts_xs_fourSixGradeTextSignUp where id='" + id + "'", con);
scd.ExecuteNonQuery();
con.Close();
this.bind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string id = GridView1.DataKeys[e.NewEditIndex].Value.ToString();
Response.Write("<script>window.open('std_addGradeTestSignUpInfoList.aspx?id=" + id + "','','width=740,height=410')</script>");
Response.Write("<script>location='javascript:history.go(-1)'</script>");
}
2.JavaScript弹出对话框
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script language=javascript>alert('回复留言失败!');</script>");
Response.Write("<script>alert('登陆成功!');history.go(-1);</script>");
3.GridView和CheckBox结合:
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (CheckBox2.Checked == true)
{cbox.Checked = true;}
else
{ cbox.Checked = false;}
}
}
4.留言板:
Gridview自定义模板
<%@ Import Namespace="System.Data" %>
<div id="div2" runat=server>
<asp:ScriptManager ID="ScriptManager1" runat="server" > </asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server"UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="200px" OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging=true PageSize="6" GridLines=None>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table border="0" cellpadding="0" height=150 width=800>
<tr><td rowspan="3" style="width:120px" >
<asp:Image ID="Image2" runat="server" ImageUrl='<%#((DataRowView)Container.DataItem)["PicUrl"]%>'/><br/>
<div id="div12" style="text-align:left">
昵称:<%# ((DataRowView)Container.DataItem)["UserName"]%>
E-mail:<%# ((DataRowView)Container.DataItem)["userEmail"]%>
来自:<%# ((DataRowView)Container.DataItem)["UserIP"].ToString().Substring(0, ((DataRowView)Container.DataItem)["UserIP"].ToString().LastIndexOf(".")+1)%>
</div></td>
<td colspan="2" style="height: 20px; text-align:left;">
<asp:Image ID="Image3" runat="server" ImageUrl='<%# ((DataRowView)Container.DataItem)["faceurl"]%>'/>
发表于:<%# ((DataRowView)Container.DataItem)["Addtime"]%>
</td></tr>
<tr><td colspan="2" valign="top" height="50" style="text-align:left;">
<%# ((DataRowView)Container.DataItem)["UserContent"] %>
<div id="main1" style="margin-top:40px;border:#ff9966 1px solid;" visible='<%#(((DataRowView)Container.DataItem)["adminReply"]).ToString()==""?false:true %>' runat=server > <font color=red> 管理员回复:<br/><%# ((DataRowView)Container.DataItem)["adminReply"]%></font> </div>
</td></tr></table>
</ItemTemplate>
</asp:TemplateField>
</Columns></asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="PageIndexChanging"/>
</Triggers>
</asp:UpdatePanel>
</div>
5.从一个另外一个页面获取获取gridveiw中数据
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="8" AutoGenerateColumns="False" EmptyDataText="暂时没有留言" OnPageIndexChanging="GridView1_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None" Width="700px" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="id"//绑定到超链接的属性字段DataNavigateUrlFormatString="UserInfo.aspx?id={0}"
//对绑定的超链接NavigateUrl属性值的格式设置以便在UserInfo.aspx页面用Request.QueryString["id"]获取gridview的指定列主键id
{public void init()
{ //用Request.QueryString["id"].ToString()获取gridview的主键id
string id = Request.QueryString["id"].ToString();
if (id != null && id != "")
{
string sql = "select * from message where id=" + id;
DataSet ds = db.GetData(sql, "message");
this.username.Text = ds.Tables["message"].Rows[0]["username"].ToString();
//DataRowView rv = ds.Tables["0"].DefaultView[0];
//this.username.Text = rv["username"].ToString();
}
}
DataTextField="username" HeaderText="用户" Target="_self" />
<asp:BoundField DataField="useremail" HeaderText="邮件" />
<asp:BoundField DataField="userurl" HeaderText="个人网站" />
<asp:CommandField ShowDeleteButton="True" /> </Columns>
</asp:GridView>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnViewStudents" runat="server" CommandArgument='<%#Eval("pc_id")%>'>查看选课学生</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
#region 查看选课学生
protected void gv_TeachCoures_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("ViewStudentChoose.aspx?pc_id=" + e.CommandArgument.ToString());
}
#endregion
<asp:TemplateField>
<HeaderTemplate >
教师编号
</HeaderTemplate>
<ItemTemplate >
<a id="A1" href= "#"
onclick='javascript:showDetail(<%#DataBinder.Eval(Container.DataItem, "id")%>);'><font style=" text-decoration: underline;"><asp:label id= "laid" runat= "server" Text= '<%#Bind("jsgh")%>' Width="160px"> </asp:label>
</font></a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="编辑">
<ItemTemplate>
<asp:Button ID='ButtonD' runat="server" CssClass="button" CommandName="del" CommandArgument=<%#bind("id")%> Text="删除" />
</ItemTemplate>
</asp:TemplateField>
/// 删除事件
protected void gvTeacher_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "del")
{
int id = Convert.ToInt32(e.CommandArgument.ToString());
teacherBll.Delete(id);
this.pager.CurPage = this.ddlstPage.SelectedIndex + 1;
this.strWhere = this.hfdQeuryCondition.Value;
FillGridView();
}
}
6.删除gridveiw选中行
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sql = "select * from message";
OleDbDataAdapter da = new OleDbDataAdapter(sql,conn);
OleDbCommandBuilder oc = new OleDbCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds,"b");
DataRow row = ds.Tables["b"].Rows[e.RowIndex];
row.Delete();
da.Update(ds,"b");
this.ShowInfo();
}
7.//设置gridview中指定列的内容和鼠标移动是改变行颜色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//int i;
////执行循环,保证每条数据都可以更新
//for (i = 0; i < GridView1.Rows.Count; i++)
//{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='#E6F5FA'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
if (e.Row.Cells[4].Text.Trim() == "0")
{
{e.Row.Cells [4].Text=" <font color=red>隐藏</font>";}
else
{e.Row .Cells[4].Text="公开";}
} ((LinkButton)(e.Row.Cells[6].Controls[0])).Attributes.Add("onclick","return confirm('确定要删除吗?')");
}
}
8.GridView实现删除时弹出确认对话框:
双击GridView的OnRowDataBound事件;
在后台的GridView1_RowDataBound()方法添加代码,最后代码如下所示:
protected void GridView1_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[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");
}
}
}
/// GV 数据绑定事件
protected void gvTeacher_RowDataBound(object sender, GridViewRowEventArgs e)
{
//首先判断是否是数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", " this.style.backgroundColor='#C0FAFF'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
//编辑按钮onclick事件
string url = "TeacherAdd.aspx?id=" + this.gvTeacher.DataKeys[e.Row.RowIndex].Value;
string OnClientClick = CommonPage.Fpage_f_win_opendialog_returnvalue(this.Page, url, 850, 600);
//窗口事件
public static string Fpage_f_win_opendialog_returnvalue(System.Web.UI.Page page, string URL, int width, int height)
{
string js2 = "javascript:";
js2 += string.Format("res=window.showModalDialog(\"{0}\",window,\"
status:no;resizable:no;dialogWidth:{1}px;dialogHeight:{2}px\");", URL, width.ToString(), height.ToString());
js2 += "if (res==\"pleasefresh\")" + " {" + " refresh();" + "}";
return js2;
}
例子:
//新增按钮Onclick事件字符串
string OnAddClientClick =Fpage_f_win_opendialog_returnvalue(this.Page, "TeacherAdd.aspx", 850, 600);
//绑定新增按钮btnAdd Onclick事件
this.btnAdd.Attributes.Add("onclick", OnAddClientClick);
((HtmlInputButton)e.Row.FindControl("ButtonE")).Attributes.Add("onclick", OnClientClick);
//删除按钮onclick事件
string ondeleteclick = "javascript:return confirm('是否删除教师" + e.Row.Cells[2].Text + "?')"; ((Button)e.Row.FindControl("ButtonD")).Attributes.Add("onclick",ondeleteclick;
}
}
9.GridView加入自动求和求平均值小计
private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
sum += Convert.ToDouble(e.Row.Cells[6].Text);
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[5].Text = "总薪水为:";
e.Row.Cells[6].Text = sum.ToString();
e.Row.Cells[3].Text = "平均薪水为:";
e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();
}
}
10.配置文件连接数据和取得web.config键值
<connectionStrings>
<!-- SQL connection string for Inventory database lookup -->
<add name="SQLConnetionString" connectionString="server=(local);user id=sa;password=;database=OfficeAutoDB;min pool size=4;max pool size=4;packet size=3072" providerName="System.Data.SqlClient">
</add>
</connectionStrings>
<appSettings>
<add key ="DSExcel" value="Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" ></add>
<add key="Excel" value ="App_Data\excel.xls"></add>
</appSettings>
private readonly string DSExcel = ConfigurationSettings.AppSettings["DSExcel"].ToString();
private readonly string Excel = ConfigurationSettings.AppSettings["Excel"].ToString();
public static string sqlcon = ConfigurationManager.ConnectionStrings["SQLConnetionString"].ToString();
11.GridView数据导入Excel/Excel数据读入GridView
由于是文件操作所以要引入名称空间IO和Text
using System.IO;
using System.Text;
using System.Drawing;
//导入Excel
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "学生成绩报表.xls");
}
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
//如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
public override void VerifyRenderingInServerForm(Control control)
{
}
//读取Excel数据
private DataSet CreateDataSource()
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~\\App_Data\\excel.xls") + ";Extended Properties=Excel 8.0 ;";
OleDbConnection olecon = new OleDbConnection(strCon);
// string ExcelDbPath = DSExcel + Server.MapPath(Excel) + ";";
// OleDbConnection olecon = new OleDbConnection(ExcelDbPath);
OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", olecon);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds;
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
11.GridView动态分页取出当前显示需要显示的记录
private DataSet GetCachingData(int nStartIndex, int nMaxIndex)
{
string sql = "select * from Files";
SqlConnection cn = new SqlConnection(sqlcon);
string counttext = "select count(*) as countFiles from Files";
SqlCommand cmd = new SqlCommand(counttext, cn);
SqlDataAdapter adapter = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
cn.Open();
int nMaxcount = Int32.Parse(cmd.ExecuteScalar().ToString());
int nPagecount = nMaxcount / GridView1.PageSize;
if (GridView1.PageSize * nPagecount < nMaxcount)
{
nPagecount++;
}
adapter.Fill(ds, nStartIndex, nMaxIndex, "Files");
cn.Close();
return (ds);
}
private void BindData()
{
DataSet ds = new DataSet();
if (GridView1.PageIndex == 0)
{
ds = GetCachingData(0, GridView1.PageSize);
}
else
{
if (GridView1.PageIndex > 1)
{
ds = GetCachingData((GridView1.PageIndex - 1) * GridView1.PageSize, GridView1.PageSize);
}
}
if (ds != null && ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
//选中checkbox
private ArrayList GetSelected()
{ ArrayList selected = new ArrayList();
for (int i = 0; i <= gvTeacher.Rows.Count - 1; i++)
{
if (((CheckBox)gvTeacher.Rows[i].FindControl("chkBox1")).Checked)
selected.Add(Convert.ToInt32(gvTeacher.DataKeys[i].Value));
}
return selected;
}