对于gridview学NET的同学再熟悉不过,但是其中功能事件是否能编码熟练实现?前不久看点博文,以及资料,综合自己的一些想法,汇总如下:
数据库设计如下,以便更好理解:
设计:
实现:
GridView无代码分页排序
小实例:
AllowSorting设为True,aspx代码中是AllowSorting="True";
运行结果:
GridView选中,编辑,取消,删除
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />--%>
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(); //正常绑定
}
}
/// <summary>
/// 主题:绑定数据,查询显示个人信息
/// 时间:2012年11月21日14:54:13
/// 描述:通过简单的方法绑定,实现数据显示
/// 作者:小伙
/// </summary>
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select top 5 * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
}
//实现分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.bind();
}
//删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sqlstr = "delete from person where pid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
con.Open();
cmd = new SqlCommand(sqlstr, con);
cmd.ExecuteNonQuery();
con.Close();
bind();
}
//取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
//编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
//更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlstr = "update person set pname='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',psex='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()+"',padress='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()+"',pyoubiao='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim()+"',pprice='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim()+"' where pid='"
+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
cmd = new SqlCommand(sqlstr, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}
运行结果:
运行初始页:
点击编辑:
更新后:
GridView正反双向排序
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting">
<Columns>
<%--<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortOrder"] = "pname";
ViewState["OrderDire"] = "ASC";
Sortbind1();//排序绑定
}
}
//排序绑定
public void Sortbind1()
{
string sqlstr = "select top 5 * from person";
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
con.Open();
myda.Fill(ds, "person");
DataView view = ds.Tables["person"].DefaultView;
string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
view.Sort = sort;
GridView1.DataSource = view;
GridView1.DataBind();
con.Close();
}
//排序
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sPage = e.SortExpression;
if (ViewState["SortOrder"].ToString() == sPage)
{
if (ViewState["OrderDire"].ToString() == "Desc")
{
ViewState["OrderDire"] = "ASC";
}
else
{
ViewState["OrderDire"] = "Desc";
}
}
else
{
ViewState["SortOrder"] = e.SortExpression;
}
Sortbind1();
}
运行结果:
排序前:
排序后:
GridView和下拉菜单DropDownList结合
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting">
<Columns>
<%--<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:TemplateField HeaderText="性别" SortExpression="psex" >
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSource='<%# ddlbind()%>' DataValueField="psex" DataTextField="psex"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编"
SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Drpbind();//dropdown绑定
}
}
//DropDownList绑定数据
DropDownList ddl;
public void Drpbind()
{
string sqlstr = "select top 5 * from person";
con.Open();
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, con);
DataSet ds = new DataSet();
myda.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataBind();
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv = ds.Tables["person"].DefaultView[i];
if (Convert.ToString(mydrv["psex"]).Trim() == "男")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 0;
}
else if (Convert.ToString(mydrv["psex"]).Trim() == "女")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("DropDownList1");
ddl.SelectedIndex = 1;
}
}
con.Close();
}
//GridView和下拉菜单DropDownList结合,前台性别列datasouce调用
public SqlDataReader ddlbind()
{
string sqlstr = "select distinct psex from person";//distinct只显示一次性别
using (cmd = new SqlCommand(sqlstr, con))
{
con.Close();
con.Open();
return cmd.ExecuteReader();
}
}
运行结果:
GridView和CheckBox结合
小实例:
GridView.aspx
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />--%>
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
<br />
<asp:CheckBox ID="CheckBox2" runat="server" ForeColor="Red" Text="全选"
AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" />
<asp:Button ID="Button1" runat="server" Font-Bold="true" ForeColor="red"
Text="删除" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Font-Bold="true" ForeColor="red"
Text="取消" onclick="Button2_Click" />
</form>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(); //正常绑定
}
}
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
}
//利用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;
}
}
}
//删除选中信息
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{
string sqlstr = "delete from person where pid='" + GridView1.DataKeys[i].Value + "'";
cmd = new SqlCommand(sqlstr, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
bind();
}
//取消选中信息
protected void Button2_Click(object sender, EventArgs e)
{
CheckBox2.Checked = false;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cbox.Checked = false;
}
}
运行结果:
鼠标移到GridView某一行时改变该行的背景色方法一
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />--%>
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(); //正常绑定
}
}
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
}
//鼠标移动到某一行,改变改行颜色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count+1; i++) //执行循环,保证每条数据都可以更新
{
if (e.Row.RowType == DataControlRowType.DataRow) //首先判断是否是数据行
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#999'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
}
运行结果:
鼠标移到GridView某一行时改变该行的背景色方法二
小实例:
GridView.aspx
GridView.aspx.cs
//鼠标移动到某一行,改变改行颜色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");
}
}
运行结果:
GridView实现删除时弹出确认对话框
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//鼠标移动到某一行,改变改行颜色
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
#region
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");
}
#endregion
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[7].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text + "\"吗?')");
}
}
}
运行结果:
GridView实现自动编号
小实例:
GridView.aspx
前台代码如上
GridView.aspx.cs
绑定显示数据代码如上,不再总结,以下只做主要代码:
//实现自动编号
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
#region
//如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#999'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#087'");
}
#endregion
#region
//如果是绑定数据行
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[1].Text + "\"吗?')");
}
}
#endregion
if (e.Row.RowIndex != -1)
{
int id = e.Row.RowIndex + 1;
e.Row.Cells[0].Text = id.ToString();
}
}
运行结果:
GridView实现用“...”代替超长字符串
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="证号" SortExpression="id" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
//省略字符
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv;
string gIntro;
if (GridView1.PageIndex == 0)
{
mydrv = ds.Tables["person"].DefaultView[i];
gIntro = Convert.ToString(mydrv["padress"]);
GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);
}
else
{
mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)];
gIntro = Convert.ToString(mydrv["padress"]);
GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);
}
}
}
public string SubStr(string sString, int nLeng)
{
if (sString.Length <= nLeng)
{
return sString;
}
string sNewStr = sString.Substring(0, nLeng);
sNewStr = sNewStr + "...";
return sNewStr;
}
运行结果:
GridView显示隐藏某一列
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="证号" SortExpression="id" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" AutoPostBack="true" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<%-- <asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />--%>
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
<br />
<asp:CheckBox ID="CheckBox2" runat="server" ForeColor="Red" Text="全选"
AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" />
<asp:CheckBox ID="CheckBox3" runat="server" ForeColor="Red" Text="隐藏工资起价"
AutoPostBack="True" oncheckedchanged="CheckBox3_CheckedChanged" />
<asp:Button ID="Button1" runat="server" Font-Bold="true" ForeColor="red"
Text="删除" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Font-Bold="true" ForeColor="red"
Text="取消" onclick="Button2_Click" />
GridView.aspx.cs
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
//省略字符
#region
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv;
string gIntro;
if (GridView1.PageIndex == 0)
{
mydrv = ds.Tables["person"].DefaultView[i];
gIntro = Convert.ToString(mydrv["padress"]);
GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);
}
else
{
mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)];
gIntro = Convert.ToString(mydrv["padress"]);
GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);
}
}
#endregion
//隐藏列
GridView1.Columns[7].Visible = false;//一开始隐藏
CheckBox3.Checked = false;//如果不这样后面的代码会把他True
}
//隐藏列
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
GridView1.Columns[7].Visible = !GridView1.Columns[7].Visible;
Response.Write("GridView1的第8列现在的显示隐藏状态是:" + GridView1.Columns[7].Visible.ToString());
}
运行结果:
GridView弹出新页面/弹出新窗口
小实例:
GridView.aspx
运行结果:
GridView突出显示某一单元格(工资低于10000元)
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" PageSize="4"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />
<%-- <asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />--%>
<asp:HyperLinkField HeaderText="姓名" Text="姓名" DataNavigateUrlFields="pname" DataNavigateUrlFormatString="WebForm1.aspx?GoodsID={0}" Target="mainframe" NavigateUrl="~/WebForm1.aspx" DataTextField="pname" >
</asp:HyperLinkField>
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" DataFormatString="{0:C}" SortExpression="pprice" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
//省略字符
#region
//for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
//{
// DataRowView mydrv;
// string gIntro;
// if (GridView1.PageIndex == 0)
// {
// mydrv = ds.Tables["person"].DefaultView[i];
// gIntro = Convert.ToString(mydrv["padress"]);
// GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);
// }
// else
// {
// mydrv = ds.Tables["person"].DefaultView[i + (5 * GridView1.PageIndex)];
// gIntro = Convert.ToString(mydrv["padress"]);
// GridView1.Rows[i].Cells[5].Text = SubStr(gIntro, 2);
// }
//}
#endregion
//隐藏列
//GridView1.Columns[3].Visible = false;//一开始隐藏
//CheckBox3.Checked = false;//如果不这样后面的代码会把他True
//突出显示某一单元格(工资起价少于10000)
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
DataRowView mydrv = ds.Tables["person"].DefaultView[i];
string price = Convert.ToString(mydrv["pprice"]);
if (Convert.ToDouble(price) < 10000)//大家这里根据具体情况设置可能ToInt32等等
{
GridView1.Rows[i].Cells[5].BackColor = System.Drawing.Color.Red;
}
}
}
运行结果:
GridView数据导入Excel/Excel数据读入GridView
小实例:
GridView.aspx
<asp:GridView ID="GridView1" runat="server" Height="138px" Width="1117px"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="身份证号" SortExpression="pid">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("pid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:BoundField DataField="pid" HeaderText="身份证号" SortExpression="pid" />--%>
<asp:BoundField DataField="pname" HeaderText="姓名" SortExpression="pname" />
<asp:BoundField DataField="psex" HeaderText="性别" SortExpression="psex" />
<asp:BoundField DataField="padress" HeaderText="地址" SortExpression="padress" />
<asp:BoundField DataField="pyoubiao" HeaderText="邮编" SortExpression="pyoubiao" />
<asp:BoundField DataField="pprice" HeaderText="工资起价" SortExpression="pprice" />
<asp:CommandField HeaderText="选择" ShowSelectButton="True" />
<asp:CommandField HeaderText="编辑" ShowEditButton="True" />
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<EmptyDataRowStyle BackColor="Red" />
<HeaderStyle BackColor="#0000CC" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#864" HorizontalAlign="Center" ForeColor="White"/>
</asp:GridView>
GridView.aspx.cs
//公有数据
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString);
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind(); //正常绑定
}
}
/// <summary>
/// 主题:绑定数据,查询显示个人信息
/// 时间:2012年11月21日14:54:13
/// 描述:通过简单的方法绑定,实现数据显示
/// 作者:小伙
/// </summary>
public void bind()
{
//数据连接web.config中已配置的数据
SqlDataAdapter da = new SqlDataAdapter("select top 5 * from person", con);//使用数据适配器内置查询,自动开闭数据库
DataSet ds = new DataSet();//使用数据集,采取断开式访问数据
da.Fill(ds, "person");
GridView1.DataSource = ds;
GridView1.DataKeyNames=new string[]{"pid"};//设置主键
GridView1.DataBind();
}
//实现分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.bind();
}
//删除
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sqlstr = "delete from person where pid='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
con.Open();
cmd = new SqlCommand(sqlstr, con);
cmd.ExecuteNonQuery();
con.Close();
bind();
}
//取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
//编辑
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
//更新
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlstr = "update person set pname='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',psex='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()+"',padress='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()+"',pyoubiao='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim()+"',pprice='"
+((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString().Trim()+"' where pid='"
+GridView1.DataKeys[e.RowIndex].Value.ToString()+"'";
cmd = new SqlCommand(sqlstr, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
bind();
}
运行结果:
导出结果: