您的当前位置:首页正文

(完整版)Gridview控件的使用

来源:独旅网


在Gridview中添加超链接列

进入Gridview的【编辑列…】窗口进行编辑,如图:

在【可用字段】里选择HyperLinkField,单击【添加】按钮。

然后选择在【选定的字段】中,选择刚添加的这个HyperLinkField。 在右边按照图示进行设置: 外观-Text:设置链接的文字。

外观-HeaderText:设置链接列的标题。

数据-DataNavigateUrlFields:设置超链接要传递的参数,这里写的“id,name”表示要传递id和name这两个字段的值,注意用逗号分隔,可以设置多个字段。

数据-DataNavigateUrlFormatString:设置要链接到的页面和传递的参数。Default2.aspx?id={0}&name={1}表示要链接到Default2.aspx页面。这里的{0}表示在形成链接时{0}将会被DataNavigateUrlFields中设置的第一个参数实际的值替代,在我们这里是id,{1}将会被name的实际值替代。 最终形成的页面代码如下:

DataNavigateUrlFormatString=\"Default2.aspx?id={0}&name={1}\" HeaderText=\"操作\" Text=\"修改\" />

后置代码如下: using System;

using System.Data;

using System.Configuration; using System.Collections; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa1\"); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from city\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); } }

这时,浏览页面看效果,如图:

如果把鼠标移动到超链接上,观察形成的链接,效果如图:

给Gridview添加复选框

点击Gridview右上角的三角按钮,选择【编辑列…】,添加一个TemplateField:

然后单击向上的按钮,将这个TemplateField移动到最上面:

这样,我们就为Gridview添加了一个TemplateField,并且将这个TemplateField排到第一列。 下面对这个TemplateField添加标题和内容。在【Gridview 任务】中,选择【编辑模板】:

进入模板编辑模式,选择Column[0]下的HeaderTemplate:

拖一个Checkbox标签到HeaderTemplate里:

这样就设置了列标题中的复选框。

选择Column[0]下的ItemTemplate,然后拖一个CheckBox控件到ItemTemplate里,设置这个控件的id=”element”:

形成的代码:

打开源代码视图,修改里的复选框的id=”all”,添加单击事件onclick=\"selectAll(this)\"。

里复选框的代码是这样的:

全选 完整的Gridview代码:

onclick=\"selectAll(this)\"/>全选

DataNavigateUrlFormatString=\"Default2.aspx?id={0}&name={1}\" HeaderText=\"操作\" Text=\"修改\" />

添加selectAll脚本函数:

运行页面后的效果:

当点击标题列中的复选框时,这一列的复选框都会被选择或者取消。

下面开始讲解:如何把在Gridview中选择的一行信息传递到后置代码中。 在Gridview下添加一个Button和Label控件:

给Button添加click事件,页面代码:


Button1_Click方法:

protected void Button1_Click(object sender, EventArgs e) {

Label1.Text = \"\";

//按行遍历cityList

foreach (GridViewRow gvr in cityList.Rows) {

//在每行中查找id为element的控件,强制转换成ChecBox类型 CheckBox ch = (CheckBox)gvr.FindControl(\"element\"); //检查ch,如果处于选择状态 if (ch.Checked) {

//累加Label的文本。gvr.Cells[1].Text表示得到第二个元素的文本内容

Label1.Text += \"选择的城市id为:\" + gvr.Cells[1].Text + \"
\"; }

} }

还要在Page_Load方法中添加一个if判断:当页面第一次加载时才执行对Gridview的数据绑定,如果没有这个判断的话,每次都重新绑定数据,原来的选择就失效了。 Page_Load的代码:

protected void Page_Load(object sender, EventArgs e) {

//第一次加载页面时 if (!IsPostBack) {

SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa1\"); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from city\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); } }

执行代码的效果:

在Gridview中显示图片

给t1表添加三条记录,img字段里存放的是图片的路径: INSERT INTO t1(img) VALUES('./images/1.jpg') INSERT INTO t1(img) VALUES('./images/2.jpg') INSERT INTO t1(img) VALUES('./images/3.jpg') 在项目的images目录下应该已经有对应的图片存在了。

拖一个Gridview到页面,给这个Gridview添加两列:第一列显示id字段的值,第二列显示图片:

图片列是通过TemplateField实现的。 页面代码:

图片

<%#Eval(\"img\") %>表示输出当前行的img字段的值。这个值赋给ImageUrl的属性,因为赋的值是图片的路径,图片控件就能显示对应的图片了。 后置C#代码: using System;

using System.Data;

using System.Configuration; using System.Collections; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient;

public partial class Default02 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa\"); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from t1\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); } } }

运行后的效果:

在Gridview中添加删除按钮

在Gridview中添加【删除CommandField】:

添加完后打开源代码试图,看到在节点下多了

这个控件会在Gridview的每一行形成一个[删除]超链接。单击这个超链接会触发Gridview的删除事件。

下面给Gridview添加RowDeleting事件:OnRowDeleting=\"cityList_RowDeleting\"。 RowDeleting是由单击[删除]超链接时触发。

我们的思路是这样的:单击[删除]超链接,Gridview会触发RowDeleting事件,然后在

RowDeleting的后置代码中写删除的 业务逻辑,将要删除的行删掉。这就有个问题,我们删除一行肯定是根据这一行的主键进行删除,那如何将当前行的主键传递到 cityList_RowDeleting方法中呢?

我们给Gridview添加DataKeyNames属性:DataKeyNames=\"id\"。

使用DataKeyNames属性指定表示数据源主键的字段,这里我们指定的字段是id。 当设置了DataKeyNames属性时,GridView控件用指定字段(id)的值填充它的DataKeys集合,这提供了一种访问每个行的主键的便捷方法。 aspx页面代码:

AutoGenerateColumns=\"False\" OnRowDeleting=\"cityList_RowDeleting\">

用如下C#代码,在cityList_RowDeleting方法中得到DataKeyNames的id主键值。 string id = cityList.DataKeys[e.RowIndex].Value.ToString();

C#后置代码:

using System;

using System.Data;

using System.Configuration; using System.Collections; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient;

public partial class Default04 : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

GetAll(); } }

protected void cityList_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

string id = cityList.DataKeys[e.RowIndex].Value.ToString(); SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa\"); DataSet citySet = null; try {

conn.Open();

SqlCommand cmd = new SqlCommand(\"delete from city where id = '\" + id + \"'\");

cmd.Connection = conn; cmd.ExecuteNonQuery(); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

GetAll(); }

private void GetAll() {

SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa\"); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from city\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); } }

运行aspx页面后的效果:

这样就实现了点击[删除]链接后,删掉一条记录。

删除通常是要谨慎的,最好先让操作者再确认下,然后再进行删除,以避免误操作。如何在Gridview删除前加上个确认对话框呢?

选择【删除CommandField】,点击右下角的【将此字段转换为TemplateField】链接,然后点【确定】按钮:

切换到源代码视图,发现原来的

现在变成了

然后在中添加提示脚本:

OnClientClick=\"return confirm('确认要删除吗?');\" 这时的Gridview控件代码:

AutoGenerateColumns=\"False\" OnRowDeleting=\"cityList_RowDeleting\">

OnClientClick=\"return confirm('确认要删除吗?');\">

这样在单击【删除】链接时,就会先弹出脚本提示了:

Gridview的选择、编辑、更新、取消、删除操作

选择Gridview的一行。

给Gridview添加【选择CommandField】:

然后,给Gridview添加SelectedRowStyle节点,设置被选择行的样式。 aspx代码:

C#后置代码:

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

GetAll(); } }

private void GetAll() {

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa1\";

SqlConnection conn = new SqlConnection(str); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from city\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); }

在浏览器中查看aspx页面:

单击【选择】链接后的效果:

给Gridview添加编辑、更新、取消操作。 选择【编辑、更新、取消CommandField】:

这个操作会在Gridview中生成如下代码:

运行aspx页面效果:

这时需要给Gridview添加RowEditing事件,当单击【编辑】链接时触发这个事件:

这时在Gridview中多了属性:OnRowEditing=\"cityList_RowEditing\" C#后置代码:

protected void cityList_RowEditing(object sender, GridViewEditEventArgs e) {

cityList.EditIndex = e.NewEditIndex; GetAll(); }

NewEditIndex表示选择的所要编辑的当前行的索引号,EditIndex表示告诉Gridview要对哪个行进行编辑。

cityList.EditIndex = e.NewEditIndex;就是将当前选择的要编辑的行的索引号赋给EditIndex属性,Gridview知道将对哪一行进行编辑操作。 单击【编辑】链接后的aspx页面效果:

当单击【取消】链接时会触发RowCancelingEdit事件,

所以需要给Gridview添加OnRowCancelingEdit=\"cityList_RowCancelingEdit\" C#后置代码中的方法:

protected void cityList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {

cityList.EditIndex = -1; GetAll(); }

cityList.EditIndex = -1;表示需要编辑行的索引是-1行,是不存在的,这样就保证Gridview中没有行处于可编辑状态了。

单击【更新】链接会触发RowUpdating事件,可以在RowUpdating事件的后置代码中写更新的SQL语句。

在Gridview中添加事件:OnRowUpdating=\"cityList_RowUpdating\" C#后置代码:

protected void cityList_RowUpdating(object sender, GridViewUpdateEventArgs e) {

try {

string id =

((TextBox)(cityList.Rows[e.RowIndex].Cells[0].Controls[0])).Text; string name =

((TextBox)(cityList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=\";

SqlConnection conn = new SqlConnection(str); conn.Open();

SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = \"update city set name = @name where id = @id\"; cmd.Parameters.Add(\"@id\", SqlDbType.Int).Value = Int32.Parse(id);

cmd.Parameters.Add(\"@name\", SqlDbType.VarChar).Value = name; cmd.ExecuteNonQuery(); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.EditIndex = -1; GetAll(); }

((TextBox)(cityList.Rows[e.RowIndex].Cells[0].Controls[0])).Text的解释: cityList.Rows[e.RowIndex]这部分能定位到正在编辑的当前行。 cityList.Rows[e.RowIndex].Cells[0]进一步定位到当前行的第一列。

cityList.Rows[e.RowIndex].Cells[0].Controls[0]进一步定位第一列中的第一个控件。 然后强制转换成TextBox类型,通过Text属性取得值。 下面给Gridview添加删除功能

首先要添加【删除CommandField】,如图:

这个操作会在Gridview中添加aspx代码:

还要给Gridview添加DataKeyNames=\"id\"。

删除操作会触发RowDeleting事件,所以,给Gridview添加属性:OnRowDeleting=\"cityList_RowDeleting\"

删除操作的C#后置代码:

protected void cityList_RowDeleting(object sender, GridViewDeleteEventArgs e) {

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=sa1\";

SqlConnection conn = new SqlConnection(str); try {

conn.Open();

SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;

cmd.CommandText = \"delete from city where id = @id\"; cmd.Parameters.Add(\"@id\", SqlDbType.Int).Value = cityList.DataKeys[e.RowIndex].Value.ToString(); cmd.ExecuteNonQuery(); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.EditIndex = -1; GetAll(); }

最后的aspx页面代码:

C#代码:

using System;

using System.Data;

using System.Configuration; using System.Collections; using System.Web;

using System.Web.Security; using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) {

GetAll(); } }

private void GetAll() {

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=\";

SqlConnection conn = new SqlConnection(str); DataSet citySet = null; try {

SqlDataAdapter adapter = new SqlDataAdapter(\"select * from city\", conn);

citySet = new DataSet();

adapter.Fill(citySet, \"city\"); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.DataSource = citySet; DataBind(); }

protected void cityList_RowEditing(object sender, GridViewEditEventArgs e) {

cityList.EditIndex = e.NewEditIndex; GetAll(); }

protected void cityList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {

cityList.EditIndex = -1; GetAll(); }

protected void cityList_RowUpdating(object sender, GridViewUpdateEventArgs e) {

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=\";

SqlConnection conn = new SqlConnection(str); try {

string id =

((TextBox)(cityList.Rows[e.RowIndex].Cells[0].Controls[0])).Text; string name =

((TextBox)(cityList.Rows[e.RowIndex].Cells[1].Controls[0])).Text;

conn.Open();

SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = \"update city set name = @name where id = @id\"; cmd.Parameters.Add(\"@id\", SqlDbType.Int).Value = Int32.Parse(id);

cmd.Parameters.Add(\"@name\", SqlDbType.VarChar).Value = name; cmd.ExecuteNonQuery(); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.EditIndex = -1; GetAll(); }

protected void cityList_RowDeleting(object sender, GridViewDeleteEventArgs e) {

string str = \"Data Source=.;Initial Catalog=demo;User ID=sa;Password=\";

SqlConnection conn = new SqlConnection(str); try {

conn.Open();

SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;

cmd.CommandText = \"delete from city where id = @id\"; cmd.Parameters.Add(\"@id\", SqlDbType.Int).Value = cityList.DataKeys[e.RowIndex].Value.ToString(); cmd.ExecuteNonQuery(); }

catch (SqlException ex) {

Console.WriteLine(ex.Message); }

finally {

conn.Close(); }

cityList.EditIndex = -1; GetAll(); } }

因篇幅问题不能全部显示,请点此查看更多更全内容