GridView常用操作事件图文介绍

对于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();

}

运行结果:

导出结果:

(0)

相关推荐

  • GridView常用操作事件图文介绍

    对于gridview学NET的同学再熟悉不过,但是其中功能事件是否能编码熟练实现?前不久看点博文,以及资料,综合自己的一些想法,汇总如下: 数据库设计如下,以便更好理解: 设计: 实现: GridView无代码分页排序 小实例: AllowSorting设为True,aspx代码中是AllowSorting="True": 运行结果: GridView选中,编辑,取消,删除 小实例: GridView.aspx 复制代码 代码如下: <asp:GridView ID="

  • 浅析Yii2中GridView常见操作

    本文是小编给大家收集整理些有关网络上GridView出现的大部分问题,本文做一个总结特此分享到我们平台供大家参考. 如果下面有没说到的GridView常见问题,下方留言,我会进行补充. 下拉搜索 日期格式化并实现日期可搜索 根据参数进行是否显示 链接可点击跳转 显示图片 html渲染 自定义按钮 设定宽度等样式 自定义字段 自定义行样式 增加按钮调用js操作 yii2 GridView 下拉搜索实现案例教程 yii2 GridView 日期格式化并实现日期可搜索 案例 是否显示某列案例 我们举一

  • Ubuntu 16.04 主题美化及常用软件安装操作步骤图文解说

    一.主题美化系统清理 系统更新: 安装完系统之后,需要更新一些补丁.Ctrl+Alt+T调出终端,执行一下代码: sudo apt-get update sudo apt-get upgrade 卸载libreOffice: libreOffice是ubuntu自带的开源office软件,我们一般习惯用WPS,在第二部分会说明WPS在Ubuntu中的安装 sudo apt-get remove libreoffice-common 卸载不常用软件: sudo apt-get remove thu

  • Python中字典的基础介绍及常用操作总结

    目录 1.字典的介绍 2.访问字典的值 (一)根据键访问值 (二)通过get()方法访问值 3.修改字典的值 4.添加字典的元素(键值对) 5.删除字典的元素 6.字典常见操作 1.len 测量字典中键值对的个数 2. keys 返回一个包含字典所有KEY的列表 3. values 返回一个包含字典所有value的列表 4. items 返回一个包含所有(键,值)元祖的列表 5.遍历字典的key(键) 6.遍历字典的value(值) 7.遍历字典的items(元素) 8.遍历字典的items(键

  • Python中元组的基础介绍及常用操作总结

    目录 1.元组的介绍 2.访问元组 3.修改元组(不可以修改的) 4.元组的内置函数有count,index 5.类型转换 1.将元组转换为列表 2.将元组转换为集合 1.元组的介绍 Python的元组与列表类似,不同之处在于元组的元素不能修改. 元组使用小括号,列表使用方括号. 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可. 元组的格式: tup=('a','b','c','d') 2.访问元组 元组可以使用下标索引来访问元组中的值,下标索引从0开始 例如: tup=('a','

  • Python中字符串的基础介绍及常用操作总结

    目录 1.字符串的介绍 2.字符串的下标 3.字符串切片 4.字符串find()操作 5.字符串index()操作 6.字符串count()操作 7.字符串replace()操作 8.字符串split()操作 9.字符串startswith()操作 10.字符串endswith()操作 11.字符串upper()操作 12.字符串lower()操作 13.字符串title()操作 14.字符串capitalize()操作 15.字符串strip()操作 16.字符串rfind()操作 17.字符

  • PHP常用操作类之通信数据封装类的实现

    前言 本文主要给大家介绍了关于PHP常用操作类之通信数据封装类实现的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 必要性 不管在B/S架构中,还是C/S架构中,两端的数据通信(注:这里的通信是指的网络请求和回复操作)都无可避免,因为没有数据便没有内容,没有内容,又有什么意义 :) 一般来说C/S架构通信执行流程如下: 而B/S架构通信执行流程像这样: 选择 既然数据通信,不可避免,那应该选择哪种通信方式比较好呢?目前来看服务器与客户端进行数据传输与交互的方式主要有URL

  • java基础之数组常用操作总结(必看篇)

    常用的对数组进行的操作 1.求数组中最大值,最小值 思路:假设下标为0的元素是最大值,遍历数组,依次跟max进行比较,如果有元素比这个max还大,则把这个值赋给max.最小值同样 public class TestArray{ public static void main(String[] args){ int[] arr={23,45,234,576,34,87,34,12,67}; int max=arr[0]; int min=arr[0]; for(int i=0;i<arr.leng

  • C++实现顺序表的常用操作(插入删出查找输出)

    实现顺序表的插入,删除,查找,输出操作在C语言中经常用到.下面小编给大家整理实现代码,一起看下吧 代码如下所示: #include<iostream> using namespace std; #define MAXSIZE 15 typedef int DataType; typedef struct { DataType data[MAXSIZE]; //通常用一位数组来描述顺序表的数据存储 int SeqLength; /*线性表长度*/ } SeqList; SeqList *Init

  • JavaScript数组常用操作技巧汇总

    本文实例汇总了JavaScript数组的常用操作技巧.分享给大家供大家参考.具体如下: 前言 相信大家都用惯了jquery或者underscore等这些类库中常用的数组相关的操作,如$.isArray,_.some,_.find等等方法.这里无非是对原生js的数组操作多了一些包装. 这里主要汇总一下JavaScript数组操作的常用API.相信对大家解决程序问题很有帮助. 一.性质 JavaScript中的数组是一种特殊的对象,用来表示偏移量的索引是该对象的属性,索引可能是整数.然而,这些数字索

随机推荐