girdView我想是我们在进行web编程的过程中用得太多了,可是,正是太过熟悉,可能会有一些东西我们没有意识到,下面就通过一些简单效果来走进girdView控件。
实现如下效果:
1、增加鼠标动作
2、为包含有特定值的行改变样式
3、客户端隐藏特定的列
4、一次删除多条数据
5、在gridview之外的地方显示当前的页码
说明:所用数据库为pubs数据库中的authors。界面设计如下:
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace gridView
{
public partial class _3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 1; i <=GridView1.Rows.Count; i++)
{
DropDownList1.Items.Add(i.ToString());
}
}
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType== DataControlRowType.DataRow)
{
//e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.backgroundColor='#00ffee';");
//e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00ffee';");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c;");
}
}
/// <summary>
/// 为包含有特定值的行改变样式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string lbl = Convert.ToString(DataBinder.Eval(e.Row.DataItem,"state"));
if (lbl=="CA")
{
e.Row.BackColor = System.Drawing.Color.LimeGreen;
}
}
}
/// <summary>
/// 列全部显示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
int columns = Convert.ToInt32(DropDownList1.SelectedValue);
GridView1.Columns[columns].Visible = false;
}
/// <summary>
/// 全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView1.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("itemchk");
if (!chk.Checked)
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
}
}
/// <summary>
/// 删除选中的行
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button3_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView1.Rows)
{
//设置模板中的checkbox的id为itemchk
CheckBox chk = (CheckBox)gr.FindControl("itemchk");
if (chk.Checked)
{
string id = ((Label)gr.FindControl("label1")).Text;
SqlDataSource1.DeleteCommand = "delete from authors where au_id='"+id+"'";
SqlDataSource1.Delete();
}
}
}
}
}
在显示页码部分的代码:
共<asp:Label ID="Label2" runat="server" Text="Label"><%=GridView1.PageCount %></asp:Label>
当前是<asp:Label ID="Label3" runat="server" Text="Label"><%=GridView1.PageIndex+1 %></asp:Label>
页
总结:
以前的时候都是自己写数据源,现在在做例子的例子的时候,更多是使用sqldatasource,感觉这个控件很强大,可以让手懒的朋友少写不少代码。也接触到了利用sqldatasource进行分页、数据库的操作等。