girdView我想是我們在進行web編程的過程中用得太多了,可是,正是太過熟悉,可能會有一些東西我們沒有意識到,下面就通過一些簡單效果來走進girdView控件。
實現如下效果:
1、增加鼠標動作
2、為包含有特定值的行改變樣式
3、客戶端隱藏特定的列
4、一次刪除多條數據
5、在gridview之外的地方顯示當前的頁碼
說明:所用數據庫為pubs數據庫中的authors。界面設計如下:
後台代碼:
[csharp]
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) www.2cto.com
{
string id = ((Label)gr.FindControl("label1")).Text;
SqlDataSource1.DeleteCommand = "delete from authors where au_id='"+id+"'";
SqlDataSource1.Delete();
}
}
}
}
}
在顯示頁碼部分的代碼:
[html]
共<asp:Label ID="Label2" runat="server" Text="Label"><%=GridView1.PageCount %></asp:Label>
nbsp; 當前是<asp:Label ID="Label3" runat="server" Text="Label"><%=GridView1.PageIndex+1 %></asp:Label>
作者:yjjm1990