對於gridview學NET的同學再熟悉不過,但是其中功能事件是否能編碼熟練實現?前不久看點博文,以及資料,綜合自己的一些想法,匯總如下:
設計:
實現:
GridView無代碼分頁排序
小實例:
AllowSorting設為True,aspx代碼中是AllowSorting="True";
運行結果:
小實例:
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.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.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.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.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.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();
}
運行結果:
導出結果: