GridView总结

来源:互联网 发布:php技术总监面试题 编辑:程序博客网 时间:2024/06/04 20:04

一.GridView数据显示

原理:在页面加载时,将gridview绑定数据源,以进行显示

实现:

1.       使GridView绑定数据源,可以使DataTable,DataReader等。

 

    ///<summary>

    /// gridviews实现数据源绑定

    ///</summary>

    public void Bind()

    {

        con = new SqlConnection(strcon);

        con.Open();

        SqlDataAdapter da = new SqlDataAdapter(strsql, con);

        DataSet ds = new DataSet();

        da.Fill(ds);

              GridView1.DataSource =ds;

        GridView1.DataKeyNames = newstring[] {"id" };//为了便于识别每行数据,加入键值进行分别,这里的键值时表中的主键id;

        GridView1.DataBind();

        con.Close();

}

2.       在页面加载时绑定数据源:

protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            Bind();

        }

}

3.   此时运行后显示的gridview标题是表的字段名。

这是gridview中AutoGenerateColumns="true"的作用,我们要自定义标题当然要AutoGenerateColumns="False"

然后就可以自己添加标题了:

编辑列选择bindfild添加headtext中填写标题datafield中填写表中的字段名如id,name等。

二. Gridview删除修改操作

原理:gridview属性中自带了GridView1_RowDeleting,GridView1_RowUpdating,GridView1_RowCancelingEdit等许多事件。当我们在页面中添加了这些事件按钮后就可以执行它。

实现:1.首先我们还是要添加删除,修改按钮,

编辑列-->选择ConmmandFieldà选择删除à添加

2.选择gridView属性—事件—>然后选择GridView1_RowDeleting双击会自动生成函数

3.然后再里面添加代码。注意获得所选行的键值一句

String id=Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);

E其中e.RowIndex表示你选择那一行的行数

 

   protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

        con = new SqlConnection(strcon);

        con.Open();

        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);//获取所选择行的键值

        string strsql="delete from UserInfo where id='"+id+"'";

        SqlCommand cmd = new SqlCommand(strsql, con);

        cmd.ExecuteNonQuery();

        Bind();

}

4.   最后同理。添加修改按钮,但是修改按钮中则包含的较多。其中有编辑,更新,取消三个响应事件。

-1.首先还是先添加CommandField—选择编辑,更新,取消—添加

2.在gridview事件中选择GridView1_RowEditing,GridView1_RowUpdating,GridView1_RowCancelingEdit分别双击,将自动产生消息响应函数。

3.添加代码如下:

///<summary>

    ///实现编辑   ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        GridView1.EditIndex = e.NewEditIndex;

        Bind();

 

    }

///<summary>

    ///更新数据

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        con = new SqlConnection(strcon);

        con.Open();

        string uname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString();

        string upassword = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();

        string strsql = "update UserInfo set uname='"+uname+"', upassword='"+upassword+"'where id='"+Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value)+"'";

        SqlCommand cmd = new SqlCommand(strsql, con);

        cmd.ExecuteNonQuery();

        GridView1.EditIndex = -1;

        Bind();

    }

///<summary>

    ///取消编辑

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protected void GridView1_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        Bind();

}

三. GridView鼠标移动改变颜色以及删除时弹出提示框

原理:在GridView事件GridView1_RowDataBound中添加javascrit事件。

实现:gridview属性事件中,双击GridView1_RowDataBound,自动生成函数后,添加以下代码

///<summary>

    ///当鼠标移动时改变颜色,删除时弹出确认对话框

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)//判断是数据绑定行

        {

            if (e.Row.RowState ==DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)

            {

                ((LinkButton)(e.Row.Cells[4].Controls[0])).Attributes.Add("onclick","javascript:return confirm('你确认要删除:\"" + e.Row.Cells[1].Text +"\"吗?')");

            }

        }

//鼠标移动后添加背景颜色

        int i;

        for (i = -1; i < GridView1.Rows.Count; i++)

        {

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

                e.Row.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");

                e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=c");

            }

        }

      

}

四. 添加模板控件

原理:当我们想在gridview中每一行添加一个CheckBox或则按钮时,这个时候我们就需要在添加列里编辑一个模板,然后再在模板里添加控件,而响应事件就是你控件的事件。

实现:第一步,我们当然是添加一个新列,比如我们添加一个checkBox来实现多项的选择,然后删除。编辑列,选择TemplateField—添加—HeadText命名为多选。

第二步,我们选择编辑模板,在显示里面选择column【】多选

然后再ItemTemplate框中拖入CheckBox控件CheckBox1,这里我们不需要再这里对该控件进行事件处理。

这时运行程序每行就会出现一个CheckBox.

第三步,再在gridView下面添加一个CheckBox控件checkBox2,旁边写上全选。目的是实现点击checkbox2时实现多选。然后双击CheckBox2,自动生成响应函数

  

    ///<summary>

    /// checkbox2即全选checked时将girdview控件中所有选择框点击

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    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");//搜寻每行ID为CheckBox1的CheckBox控件

            if (CheckBox2.Checked ==true)//如果CheckBox2点击了            {

                cbox.Checked = true;

            }

            else

            {

                cbox.Checked = false;

            }

        }

}

最后,我们再在GridView控件下面添加一个删除按钮,将选择到得行进行删除。

///<summary>

    ///删除按钮响应事件

    ///</summary>

    ///<param name="sender"></param>

    ///<param name="e"></param>

    protected void btn_delete_Click(object sender, EventArgs e)

    {

        con = new SqlConnection(strcon);

        con.Open();

        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 UserInfo where id='" + GridView1.DataKeys[i].Value + "'";

                SqlCommand cmd=newSqlCommand(sqlstr,con);

                cmd.ExecuteNonQuery();

               

            }

      

        }

         con.Close();

        Bind();

    }

五,添加超链接,传递另一张页面id然后修改或添加数据

原理:添加超链接控件

实现:1.添加新列,选择HyperLinkField,点击添加。HeaderText随意命名;

  <asp:HyperLinkFieldHeaderText="姓名"DataNavigateUrlFields="uname"DataTextField="uname"DataNavigateUrlFormatString="Default.aspx?passname ={0}"/>

2.对其数据绑定, DataTextField=”name”;跳转页面并传递姓名DataNavigateUrlFormatString="Default.aspx?GoodsID={0}

3. Default.aspx页面接受值。String name=Request.QueryString[passname]

六.GridViev数据导出到Excel/Excel数据导入到GridView中

实现:添加到处按钮,命名为btn_Excel,双击

protected void btn_Excel_Click(object sender, EventArgs e)

    {

        Export("application/ms-excel","学生成绩报表.xls");

}

 

private void Export(string FileType, string FileName)

    {

        Response.Charset = "GB2312";

        Response.ContentEncoding = System.Text.Encoding.UTF7;

        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());

        Response.ContentType = FileType;

        this.EnableViewState = false;

        StringWriter tw = new StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(tw);

        GridView1.RenderControl(hw);

        Response.Write(tw.ToString());

        Response.End();

}

 

  public override void VerifyRenderingInServerForm(Control control)

    {

    }

 

在GirdView页面中头部<%@Page Language="C#"AutoEventWireup="true"CodeFile="GridViewStudy.aspx.cs"Inherits="GridViewStudy"EnableEventValidation ="false" %>添加EnableEventValidation= "false"

 

有点累了,以后有时间了再添加些。

 

 

 

原创粉丝点击