灵活掌握asp.net中gridview控件的多种使用方法(下)

时间:2021-05-18

继续上篇文章的学习《灵活掌握asp.net中gridview控件的多种使用方法(上)》,在此基础上巩固gridview控件的操作使用,更上一层楼。

11.GridView实现用“...”代替超长字符串:
效果图:

解决方法:数据绑定后过滤每一行即可

for (int i = 0; i <= GridView1.Rows.Count - 1; i++){DataRowView mydrv;string gIntro;if (GridView1.PageIndex == 0){mydrv = myds.Tables["飞狐工作室"].DefaultView[i];//表名gIntro = Convert.ToString(mydrv["家庭住址"]);//所要处理的字段GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);}else{mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)];gIntro = Convert.ToString(mydrv["家庭住址"]);GridView1.Rows[i].Cells[3].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;}

后台全部代码:

using System;using System.Data;using System.Configuration;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{SqlConnection sqlcon;SqlCommand sqlcom;string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){ViewState["SortOrder"] = "身份证号码";ViewState["OrderDire"] = "ASC";bind();}}protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){GridView1.EditIndex = e.NewEditIndex;bind();}protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";sqlcon = new SqlConnection(strCon);sqlcom = new SqlCommand(sqlstr,sqlcon);sqlcon.Open();sqlcom.ExecuteNonQuery();sqlcon.Close();bind();}protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e){sqlcon = new SqlConnection(strCon);string sqlstr = "update 飞狐工作室 set 姓名='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"+ GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";sqlcom=new SqlCommand(sqlstr,sqlcon);sqlcon.Open();sqlcom.ExecuteNonQuery();sqlcon.Close();GridView1.EditIndex = -1;bind();}protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e){GridView1.EditIndex = -1;bind();}public void bind(){string sqlstr = "select top 5 * from 飞狐工作室";sqlcon = new SqlConnection(strCon);SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);DataSet myds = new DataSet();sqlcon.Open();myda.Fill(myds, "飞狐工作室");GridView1.DataSource = myds;GridView1.DataKeyNames = new string[] { "身份证号码" };GridView1.DataBind();for (int i = 0; i <= GridView1.Rows.Count - 1; i++){DataRowView mydrv;string gIntro;if (GridView1.PageIndex == 0){mydrv = myds.Tables["飞狐工作室"].DefaultView[i];gIntro = Convert.ToString(mydrv["家庭住址"]);GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);}else{mydrv = myds.Tables["飞狐工作室"].DefaultView[i + (5 * GridView1.PageIndex)];gIntro = Convert.ToString(mydrv["家庭住址"]);GridView1.Rows[i].Cells[3].Text = SubStr(gIntro, 2);}}sqlcon.Close();}public string SubStr(string sString, int nLeng){if (sString.Length <= nLeng){return sString;}string sNewStr = sString.Substring(0, nLeng);sNewStr = sNewStr + "...";return sNewStr;}protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e){//如果是绑定数据行if (e.Row.RowType == DataControlRowType.DataRow){////鼠标经过时,行背景色变//e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#E6F5FA'");////鼠标移出时,行背景色变//e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");////当有编辑列时,避免出错,要加的RowState判断//if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)//{// ((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:/"" + e.Row.Cells[1].Text + "/"吗?')");//}}if (e.Row.RowIndex != -1){int id = e.Row.RowIndex + 1;e.Row.Cells[0].Text = id.ToString();}}}

12.GridView一般换行与强制换行:

效果图:


首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址" ItemStyle-Width="100" />
gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。

如果要给所有的列增加此属性:

protected void Page_Load(object sender, EventArgs e){//正常换行GridView1.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");//下面这行是自动换行GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");if (!IsPostBack){bind();//调用数据绑定即可}}

总之:善用CSS的word-break:break-all;word-wrap:break-word属性即可,这个属性是通用的对于顽固的南换行问题都可以解决,不局限于GridView。

13.GridView显示隐藏某一列:
本方案为月儿独创,不同于网上其他方式,我觉得用一个CheckBox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!

效果图:

图1-开始

图2-点击显示的CheckBox后

解决方案:

public void bind(){string sqlstr = "select top 5 * from 飞狐工作室";sqlcon = new SqlConnection(strCon);SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);DataSet myds = new DataSet();sqlcon.Open();myda.Fill(myds, "飞狐工作室");GridView1.DataSource = myds;GridView1.DataKeyNames = new string[] { "身份证号码" };GridView1.DataBind();sqlcon.Close();GridView1.Columns[3].Visible = false;//一开始隐藏CheckBox1.Checked = false;//如果不这样后面的代码会把他True}双击CheckBox1,在CheckedChanged方法里写上代码,最后代码如下:protected void CheckBox1_CheckedChanged(object sender, EventArgs e){GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());}

注意:CheckBox1的AutoPostBack要True!

后台全部代码如下:

using System;using System.Data;using System.Configuration;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{SqlConnection sqlcon;SqlCommand sqlcom;string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){ViewState["SortOrder"] = "身份证号码";ViewState["OrderDire"] = "ASC";bind();}}protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){GridView1.EditIndex = e.NewEditIndex;bind();}protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";sqlcon = new SqlConnection(strCon);sqlcom = new SqlCommand(sqlstr,sqlcon);sqlcon.Open();sqlcom.ExecuteNonQuery();sqlcon.Close();bind();}protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e){sqlcon = new SqlConnection(strCon);string sqlstr = "update 飞狐工作室 set 姓名='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',家庭住址='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where 身份证号码='"+ GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";sqlcom=new SqlCommand(sqlstr,sqlcon);sqlcon.Open();sqlcom.ExecuteNonQuery();sqlcon.Close();GridView1.EditIndex = -1;bind();}protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e){GridView1.EditIndex = -1;bind();}public void bind(){string sqlstr = "select top 5 * from 飞狐工作室";sqlcon = new SqlConnection(strCon);SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);DataSet myds = new DataSet();sqlcon.Open();myda.Fill(myds, "飞狐工作室");GridView1.DataSource = myds;GridView1.DataKeyNames = new string[] { "身份证号码" };GridView1.DataBind();sqlcon.Close();GridView1.Columns[3].Visible = false;CheckBox1.Checked = false;}protected void CheckBox1_CheckedChanged(object sender, EventArgs e){GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());}}

前台代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://;string strCon = "Data Source=(local);Database=北风贸易;Uid=sa;Pwd=sa";protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){bind();}}public void bind(){string sqlstr = "select top 5 * from 飞狐工作室";sqlcon = new SqlConnection(strCon);SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);DataSet myds = new DataSet();sqlcon.Open();myda.Fill(myds, "飞狐工作室");GridView1.DataSource = myds;GridView1.DataKeyNames = new string[] { "身份证号码" };GridView1.DataBind();sqlcon.Close();}protected void Button1_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){}}

前台:

<asp:GridView ID="GridView1" runat="server" CellPadding="3"BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" Font-Size="12px" ><FooterStyle BackColor="White" ForeColor="#000066" /><Columns><asp:BoundField DataField="身份证号码" HeaderText="编号" ReadOnly="True" /><asp:BoundField DataField="姓名" HeaderText="姓名" /><asp:BoundField DataField="出生日期" HeaderText="邮政编码" /><asp:BoundField DataField="家庭住址" HeaderText="家庭住址" /><asp:BoundField DataField="邮政编码" HeaderText="邮政编码" /><asp:BoundField DataField="起薪" HeaderText="起薪" /></Columns><RowStyle ForeColor="#000066" /><SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" CssClass="ms-formlabel DataGridFixedHeader"/><HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" /></asp:GridView><asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出" />

读取Excel数据的代码:这个很简单的

private DataSet CreateDataSource(){string strCon;strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("excel.xls") + "; Extended Properties=Excel 8.0;";OleDbConnection olecon = new OleDbConnection(strCon);OleDbDataAdapter myda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strCon);DataSet myds = new DataSet();myda.Fill(myds);return myds;}protected void Button1_Click(object sender, EventArgs e){GridView1.DataSource = CreateDataSource();GridView1.DataBind();}

为大家附3个精彩的专题:

ASP.NET控件使用手册

ASP.NET数据绑定控件使用汇总

ASP.NET控件使用汇总

以上就是关于asp.net中gridview控件的多种使用方法,很全面,目的就是想让亲们玩转gridview控件,希望大家喜欢小编整理的这两篇文章。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章