GridView使用集合
来源:互联网 发布:300英雄淘宝 编辑:程序博客网 时间:2024/06/04 17:47
一、表头表尾
1、自定义多行表头,列合并,行合并
关键代码:
/// <summary> /// 在 GridView 控件中创建新行时发生,此事件通常用于在创建某个行时修改该行的布局或外观 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { switch (e.Row.RowType) { //判断是否表头 case DataControlRowType.Header: //第一行表头 TableCellCollection tcHeader = e.Row.Cells; tcHeader.Clear(); tcHeader.Add(new TableHeaderCell()); tcHeader[0].Attributes.Add("rowspan", "2"); tcHeader[0].Attributes.Add("bgcolor", "Azure"); tcHeader[0].Text = "编号"; tcHeader.Add(new TableHeaderCell()); tcHeader[1].Attributes.Add("colspan", "6"); tcHeader[1].Attributes.Add("bgcolor", "Azure"); tcHeader[1].Text = "基 本 信 息"; tcHeader.Add(new TableHeaderCell()); tcHeader[2].Attributes.Add("bgcolor", "Azure"); tcHeader[2].Text = "福利</th></tr><tr>"; //第二行表头 tcHeader.Add(new TableHeaderCell()); tcHeader[3].Attributes.Add("bgcolor", "Azure"); tcHeader[3].Text = "账号"; tcHeader.Add(new TableHeaderCell()); tcHeader[4].Attributes.Add("bgcolor", "Azure"); tcHeader[4].Text = "姓名"; tcHeader.Add(new TableHeaderCell()); tcHeader[5].Attributes.Add("bgcolor", "Azure"); tcHeader[5].Text = "性别"; tcHeader.Add(new TableHeaderCell()); tcHeader[6].Attributes.Add("bgcolor", "Azure"); tcHeader[6].Text = "住址"; tcHeader.Add(new TableHeaderCell()); tcHeader[7].Attributes.Add("bgcolor", "Azure"); tcHeader[7].Text = "邮编"; tcHeader.Add(new TableHeaderCell()); tcHeader[8].Attributes.Add("bgcolor", "Azure"); tcHeader[8].Text = "生日"; tcHeader.Add(new TableHeaderCell()); tcHeader[9].Attributes.Add("bgcolor", "Azure"); tcHeader[9].Text = "月薪"; break; } }
效果图:
2、删除表身指定列、行
关键代码:
/// <summary> /// check /// </summary> private void gvRender() { if (GridView1.Rows.Count <= 1) { return; } for (int i = 0; i < GridView1.Columns.Count; i++) { TableCell oldtc = GridView1.Rows[0].Cells[i]; for (int j = 1; j < GridView1.Rows.Count; j++) { TableCell newtc = GridView1.Rows[j].Cells[i]; if (newtc.Text == oldtc.Text) { newtc.Visible = false; if (oldtc.RowSpan == 0) { oldtc.RowSpan = 1; oldtc.RowSpan = oldtc.RowSpan + 1; oldtc.VerticalAlign = VerticalAlign.Middle; } else { oldtc = newtc; } } } } }
效果图:
3、固定表头,向下拉动滚动条时,表头固定不动
关键代码:
function init() { var bodyGridView = document.getElementById("<%=GridView1.ClientID%>"); var headGridView = bodyGridView.cloneNode(true); for (i = headGridView.rows.length - 1; i > 0; i--) headGridView.deleteRow(i); bodyGridView.deleteRow(0); //删掉数据行 headdiv.appendChild(headGridView); //删掉表头行 } window.onload = init;
<div id="headdiv" style="top: 16px; text-align:center; left: 152px; position: absolute; width: 629px;height: 21px;word-wrap:break-word; overflow:hidden;"></div><!--不需要显示表头水平滚动条--> <div id="bodydiv" style="top: 33px; left: 152px; position: absolute; width: 647px;height: 300px; overflow: auto" onscroll="headdiv.scrollLeft=scrollLeft"><!--表体的水平滚动条拖动触发表头的水平滚动事件-->
效果图:
4、表脚行统计,总计、平均值
关键代码:
double sum = 0; protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex >= 0) { sum += Convert.ToDouble(e.Row.Cells[7].Text); } else if (e.Row.RowType == DataControlRowType.Footer) { e.Row.Cells[5].Text = "总薪水:"; e.Row.Cells[6].Text = sum.ToString(); e.Row.Cells[3].Text = "平均薪水:"; e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString(); } foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; } if (e.Row.RowIndex != -1) { int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1; e.Row.Cells[0].Text = id.ToString(); } }
效果图:
二、导入导出
1、导出Excel,Word
/// <summary> /// 导出Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e) { Export("application/ms-excel", "Employee information.xls"); } /// <summary> /// 定义导出Excel的函数 /// </summary> /// <param name="FileType"></param> /// <param name="FileName"></param> private void Export(string FileType, string FileName) { Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8; 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(); } /// <summary> /// 此方法必重写,否则会出错 /// </summary> /// <param name="control"></param> public override void VerifyRenderingInServerForm(Control control) { } protected void Button2_Click(object sender, EventArgs e) { //Export("application/ms-excel", "Employee.doc"); Export("application/ms-word", "员工信息.doc");//都可以 }
效果图:
2、导入Excel
关键代码:
/// <summary> /// 以Excel为数据源获取数据集 /// </summary> /// <returns></returns> private DataSet createDataSource() { string strCon; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("~/Files/Employee.xls") + ";Extended Properties=Excel 8.0;"; OleDbConnection con = new OleDbConnection(strCon); OleDbDataAdapter da = new OleDbDataAdapter("select * from [Employee$]", con); DataSet ds = new DataSet(); da.Fill(ds); return ds; }
效果图:
三、多层嵌套
1、在父GridView中的编辑模板中嵌套一个子GridView
关键代码:
<asp:GridView ID="ParentGridView" BorderColor="Black" OnRowDataBound="ParentGridView_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True" OnRowEditing="ParentGridView_RowEditing" OnRowCancelingEdit="ParentGridView_RowCancelingEdit"> <Columns> <asp:BoundField DataField="CategoryID" HeaderText="编号" ReadOnly="True"/> <asp:BoundField DataField="CategoryName" HeaderText="类别" ReadOnly="True" /> <asp:TemplateField HeaderText="查看详情"> <ItemTemplate> <asp:Button ID="ViewChild_Button" runat="server" Text="Details" CommandName="Edit" /> </ItemTemplate> <EditItemTemplate> <asp:Button ID="CancelChild_Button" runat="server" Text="Cancel" CommandName="Cancel" /> <asp:GridView ID="ChildGridView" runat="server" AllowPaging="True" PageSize="3" AutoGenerateColumns="False" BorderColor="Black" OnRowDataBound="ChildGridView_RowDataBound" Width="241px" > <Columns> <asp:BoundField DataField="ProductID" HeaderText="编号" ReadOnly="True"/> <asp:BoundField DataField="ProductName" HeaderText="名称" ReadOnly="True" SortExpression="ProductName" /> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView> </EditItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView>
效果图:
2、三层GridView嵌套
关键代码:
<asp:GridView ID="ParentGridView" BorderColor="Black" OnRowDataBound="ParentGridView_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True" OnRowEditing="ParentGridView_RowEditing" OnRowCancelingEdit="ParentGridView_RowCancelingEdit"> <Columns> <asp:BoundField DataField="CategoryID" HeaderText="编号" ReadOnly="True"/> <asp:BoundField DataField="CategoryName" HeaderText="类别" ReadOnly="True" /> <asp:TemplateField HeaderText="查看详情"> <ItemTemplate> <asp:Button ID="ViewChild_Button" runat="server" Text="Details" CommandName="Edit" /> </ItemTemplate> <EditItemTemplate> <asp:Button ID="CancelChild_Button" runat="server" Text="Cancel" CommandName="Cancel" /> <asp:GridView ID="ChildGridView" runat="server" AllowPaging="True" PageSize="3" AutoGenerateColumns="False" OnRowEditing= "ChildGridView_OnRowEditing" BorderColor="Black" OnRowDataBound="ChildGridView_RowDataBound" DataKeyNames="ProductID" DataSourceID="AccessDataSource1" Width="241px" > <Columns> <asp:BoundField DataField="ProductName" HeaderText="名称" ReadOnly="True" SortExpression="ProductName" /> <asp:TemplateField HeaderText="查看详情"> <ItemTemplate> <asp:Button ID="ViewGrantChild_Button" runat="server" Text="Details" CommandName="Edit" /> </ItemTemplate> <EditItemTemplate> <asp:Button ID="CancelGrantChild_Button" runat="server" Text="Cancel" CommandName="Cancel" /> <asp:GridView ID="GrantChildGridView" runat="server" AllowPaging="True" PageSize="3" AutoGenerateColumns="False" BorderColor="Black" OnRowDataBound="ChildGridView_RowDataBound" DataKeyNames="ID" Width="331px" DataSourceID="AccessDataSource1" > <Columns> <asp:BoundField DataField="OrderID" HeaderText="订单号" ReadOnly="true" SortExpression="OrderID" ItemStyle-Width="100px" /> <asp:BoundField DataField="OrderMoney" HeaderText="金额" ReadOnly="true" SortExpression="OrderMoney" ItemStyle-Width="80px"/> <asp:BoundField DataField="OrderState" HeaderText="状态" ReadOnly="true" SortExpression="OrderState" ItemStyle-Width="80px"/> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Example.mdb" SelectCommand="SELECT * FROM [Orders] WHERE ([ProductID] = ?)"> <SelectParameters> <asp:SessionParameter Name="ProductID" SessionField="sProductID" Type="Int32" /> </SelectParameters> </asp:AccessDataSource> </EditItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView> </EditItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView>
效果图:
四、分页排序
1、分页
关键代码:
<asp:LinkButton ID="lnkbtnFrist" runat="server" OnClick="lnkbtnFrist_Click">首页</asp:LinkButton> <asp:LinkButton ID="lnkbtnPre" runat="server" OnClick="lnkbtnPre_Click">上一页</asp:LinkButton> <asp:Label ID="lblCurrentPage" runat="server"></asp:Label> <asp:LinkButton ID="lnkbtnNext" runat="server" OnClick="lnkbtnNext_Click">下一页</asp:LinkButton> <asp:LinkButton ID="lnkbtnLast" runat="server" OnClick="lnkbtnLast_Click">尾页</asp:LinkButton> 跳转到第<asp:DropDownList ID="ddlCurrentPage" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> </asp:DropDownList>页
效果图:
2、列排序,点击列升序、降序排序
关键代码:
/// <summary> /// 在单击某个用于对列进行排序的超链接时发生,但在 GridView 控件执行排序操作之前。此事件通常用于取消排序操作或执行自定义的排序例程。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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; } bind(); }
效果图:
五、结合控件
1、CheckBox控件,多选、全选
/// <summary> /// 当复选框被点击时发生 /// </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")); if (CheckBox2.Checked == true) { cbox.Checked = true; } else { cbox.Checked = false; } } }
效果图:
2、DropDownList控件
关键代码:
/// <summary> /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //行绑定DropDownList if (((DropDownList)e.Row.FindControl("DDLSex")) != null) { DropDownList ddlSex = (DropDownList)e.Row.FindControl("DDLSex"); ddlSex.Items.Clear(); ddlSex.Items.Add(new ListItem("男", "男")); ddlSex.Items.Add(new ListItem("女", "女")); //DropDownList初始被选择的项 ddlSex.SelectedValue = ((HiddenField)e.Row.FindControl("HDFSex")).Value; } if (((DropDownList)e.Row.FindControl("DDLAddress")) != null) { DropDownList ddlAddress = (DropDownList)e.Row.FindControl("DDLAddress"); DataSet ds = Common.dataSet("select Address from Address"); ddlAddress.DataSource = ds.Tables[0].DefaultView; ddlAddress.DataTextField = "Address"; ddlAddress.DataValueField = "Address"; ddlAddress.DataBind(); //当更改时,绑定第一个为它所属的分类 ddlAddress.SelectedValue = ((HiddenField)e.Row.FindControl("HDFAddress")).Value; } foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; } }
效果图:
3、隐藏控件,当选择处理状态选中备注时,隐藏textbox显示
关键代码:
function ddlChanged() { var e=event.srcElement;//获取鼠标点击的元素 var r=e.parentElement.parentElement.rowIndex+1;//获取元素所在的行的行号 var id='GridView1$ctl0'+r+'$txtNote';//获取TextBox的ID,由于TextBox是在Gridview里面的,所以他的 //ID会变成这样的格式,GridView的ID加上控件所在的行号加上TextBox的ID var obj=document.getElementById(id); var index=e.selectedIndex; if(index==2)//如果选择的是第三项,即备注,则显示TextBox { obj.style.display='block'; obj.select(); } else //如果选择的是其他的项,即备注,则隐藏TextBox { obj.style.display='none'; } }
效果图:
4、radio控件,选中获取GridView表主键
<asp:TemplateField HeaderText="选择"> <ItemTemplate> <input name="MyRadioButton" type="radio" value='<%# Eval("EmpID") %>' /> </ItemTemplate> </asp:TemplateField>
protected void Button1_Click(object sender, EventArgs e) { string selectedValue = Request.Form["MyRadioButton"]; Response.Write(selectedValue); }
效果图:
5、GridView中DropDownList绑定数据,直接绑定显示,无需点击编辑按纽。
关键代码:
/// <summary> /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; } // DataTable myTable = new DataTable(); DataColumn productIDColum = new DataColumn("ProductID"); DataColumn productNameColumn = new DataColumn("ProductName"); myTable.Columns.Add(productIDColum); myTable.Columns.Add(productNameColumn); string sqlProduct=@"select p.CategoryID,p.ProductID,p.ProductName from Products p"; DataSet ds = Common.dataSet(sqlProduct); int categoryID=0; string express=String.Empty; if(e.Row.RowType==DataControlRowType.DataRow) { categoryID=Int32.Parse(e.Row.Cells[0].Text); express="CategoryID="+categoryID; DropDownList ddl=(DropDownList)e.Row.FindControl("DropDownList1"); DataRow[] rows=ds.Tables[0].Select(express); foreach(DataRow row in rows) { DataRow newRow=myTable.NewRow(); newRow["ProductID"]=row["ProductID"]; newRow["ProductName"]=row["ProductName"]; myTable.Rows.Add(newRow); } ddl.DataSource=myTable; ddl.DataTextField="ProductName"; ddl.DataValueField="ProductID"; ddl.DataBind(); } }
效果图:
6、JavaScript操作checbox实现全选,多选
关键代码:
//先获取所有的Checkbox var chkList = document.getElementsByName("CheckBox1");window.onload = function(){//为所有checkbox添加onclick事件处理,以自动更新“已选择的项”for(var i=0; i<chkList.length; i++){chkList[i].onclick = chkClick;}}//checkbox的onclick事件,用于更新“已选择的项”function chkClick(){var checkedList = "";//获取所有被选中的项for(var i=0; i<chkList.length; i++){if(chkList[i].checked)checkedList += chkList[i].value + ",";}//把选中项的列表显示到“已选择的项”中,substring在这里是为了去除最后一个逗号document.getElementById("HiddenField1").value = checkedList.substring(0,checkedList.length-1);} function checkAll() { var chkall=document.getElementById("CheckBoxAll"); if(chkall.checked) { var checkedList = ""; for(var i=0;i<chkList.length;i++) { chkList[i].checked=true; checkedList += chkList[i].value + ","; } document.getElementById("HiddenField1").value = checkedList.substring(0,checkedList.length-1); } else { for(var i=0;i<chkList.length;i++) chkList[i].checked=false; document.getElementById("HiddenField1").value=""; } }
效果图:
六、设置属性
1、JavaScript设置GridView行的背景颜色,单偶行的背景颜色,鼠标停留行背景,鼠标选中时的行背景
关键代码:
//把事件放在onload里,//使用<%=%>方式输出GridView的ID是因为某些情况下(如使用了MasterPage)会造成HTML中ID的变化//颜色值推荐使用Hex,如 #f00 或 #ff0000window.onload = function(){GridViewColor("<%=GridView1.ClientID%>","#fff","#eee","#6df","#fd6");}//参数依次为(后两个如果指定为空值,则不会发生相应的事件)://GridView ID, 正常行背景色,交替行背景色,鼠标指向行背景色,鼠标点击后背景色function GridViewColor(GridViewId, NormalColor, AlterColor, HoverColor, SelectColor){//获取所有要控制的行var AllRows = document.getElementById(GridViewId).getElementsByTagName("tr");//设置每一行的背景色和事件,循环从1开始而非0,可以避开表头那一行for(var i=1; i<AllRows.length; i++){//设定本行默认的背景色AllRows[i].style.background = i%2==0?NormalColor:AlterColor;//如果指定了鼠标指向的背景色,则添加onmouseover/onmouseout事件//处于选中状态的行发生这两个事件时不改变颜色if(HoverColor != ""){AllRows[i].onmouseover = function(){if(!this.selected)this.style.background = HoverColor;}if(i%2 == 0){AllRows[i].onmouseout = function(){if(!this.selected)this.style.background = NormalColor;}}else{AllRows[i].onmouseout = function(){if(!this.selected)this.style.background = AlterColor;}}}//如果指定了鼠标点击的背景色,则添加onclick事件//在事件响应中修改被点击行的选中状态if(SelectColor != ""){AllRows[i].onclick = function(){this.style.background = this.style.background==SelectColor?HoverColor:SelectColor;this.selected = !this.selected;}}}}
效果图:
2、GridView的JavaScript中的行单击,双击、删除提示框、快捷键事件
关键代码:
function DbClickEvent(d) { window.alert("事件类型:DoubleClick作用对象:"+d); } function ClickEvent(d) { window.alert("事件类型: OnClick 作用对象: " + d); } function GridViewItemKeyDownEvent(d) { window.alert("事件类型: GridViewItemKeyDownEvent 作用对象: " + d); } //按Alt + (1 to 5)运行 function KeyDownEvent() { if( event.altKey && event.keyCode > 48 && event.keyCode < 54 ) { window.alert("事件类型: FormKeyDownEvent 选中记录数: " + ( parseInt(event.keyCode) - 48 )); } }
/// <summary> /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //如果是绑定数据行,添加确认对话框 //<asp:Button ID="btnRefuse" runat="server" OnClick="btnRefuse_Click" Text="拒绝" OnClientClick="return confirm(' 你真的要删除?')"/> if (e.Row.RowType == DataControlRowType.DataRow) { //鼠标移动到每项时颜色交替效果 e.Row.Attributes.Add("OnMouseOut", "this.style.backgroundColor='White';this.style.color='#003399'"); e.Row.Attributes.Add("OnMouseOver", "this.style.backgroundColor='#6699FF';this.style.color='#8C4510'"); //不能同时测试:单击/双击 事件, 要分别测试它们 //e.Row.Attributes.Add("OnDblClick", "DbClickEvent('" + e.Row.Cells[1].Text + "')"); e.Row.Attributes.Add("OnClick", "ClickEvent('" + e.Row.Cells[1].Text + "')"); //e.Row.Attributes.Add("OnKeyDown", "GridViewItemKeyDownEvent('" + e.Row.Cells[1].Text + "')"); e.Row.Attributes["style"] = "Cursor:hand"; 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 + "\"吗?')"); } } //遍历所有行设置边框样式 foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; //单击鼠标可以将单元格中的内容复制到剪切板 tc.Attributes.Add("onclick", "window.clipboardData.setData('Text', this.innerText);"); //鼠标移入可以设置单元格字体颜色 tc.Attributes.Add("onmouseover", "this.style.color='red'"); //鼠标移开,取消单元格字体颜色设置 tc.Attributes.Add("onmouseout", "this.style.color=''"); } //用索引来取得编号 if (e.Row.RowIndex != -1) { int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1; e.Row.Cells[0].Text = id.ToString(); } }
效果图:
3、GridView设置属性,单元格文本颜色,单元格背景颜色,表中增加空行
关键代码:
/// <summary> /// 在 GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //每5行记录后增加一个空行 if (e.Row.RowIndex > 0 && (e.Row.RowIndex + 1) % 5 == 0) { GridViewRow newRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal); newRow.Cells.Add(new TableCell()); newRow.Cells[0].ColumnSpan = e.Row.Cells.Count; newRow.Cells[0].Text = " "; this.GridView1.Controls[0].Controls.Add(newRow); } //如果是绑定数据行,添加确认对话框 //<asp:Button ID="btnRefuse" runat="server" OnClick="btnRefuse_Click" Text="拒绝" OnClientClick="return confirm(' 你真的要删除?')"/> 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 + "\"吗?')"); } } //遍历所有行设置边框样式 foreach (TableCell tc in e.Row.Cells) { tc.Attributes["style"] = "border-color:Black"; } //用索引来取得编号 if (e.Row.RowIndex != -1) { int id = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1; e.Row.Cells[0].Text = id.ToString(); } //设置具备某条件特定行的样式 for (int i = -1; i < GridView1.Rows.Count; i++) { string lbl = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpSex")); if (lbl == "女") { e.Row.Cells[3].ForeColor = Color.Fuchsia; } } //判定当前的行是否属于datarow类型的行 if (e.Row.RowType == DataControlRowType.DataRow) { //当鼠标放上去的时候 先保存当前行的背景颜色并给附一颜色 e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='Azure',this.style.fontWeight='';"); //当鼠标离开的时候 将背景颜色还原的以前的颜色 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';"); } //掩藏字段的处理 e.Row.Cells[0].Visible = false; }
效果图:
七、无代码
GridView排序、发送邮件、点击行查看详情,内容过长截取
<asp:TemplateField HeaderText="住址" SortExpression="EmpAddress"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("EmpAddress") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("EmpAddress").ToString().Length>4?Eval("EmpAddress").ToString().Substring(0,4)+"...":Eval("EmpAddress").ToString() %>'></asp:Label> </ItemTemplate> <ControlStyle Width="70px" /> <ItemStyle Width="70px" /> </asp:TemplateField> <asp:BoundField DataField="EmpZipCode" HeaderText="邮编" SortExpression="EmpZipCode" NullDisplayText="暂无资料"> <ItemStyle Width="60px" /> <ControlStyle Width="60px" /> </asp:BoundField> <asp:BoundField DataField="EmpBirthday" HeaderText="生日" HtmlEncode="False" SortExpression="EmpBirthday" DataFormatString="{0:d}"> <ItemStyle Width="80px" /> <ControlStyle Width="80px" /> </asp:BoundField> <asp:BoundField DataField="EmpSalary" DataFormatString="{0:c}" HeaderText="薪水" HtmlEncode="False" SortExpression="EmpSalary"> <ItemStyle Width="80px" /> <ControlStyle Width="80px" /> </asp:BoundField> <asp:CommandField HeaderText="编辑" ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True"> <ItemStyle Width="80px" /> </asp:CommandField> <asp:TemplateField HeaderText="发送邮件"> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "mailto:"+Eval("EmpEmail") %>' Text='<%# Eval("EmpEmail") %>' ImageUrl='<%# "~/Images/Email.gif" %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="详情"> <ItemTemplate> <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl='<%# "Details.aspx?ID="+Eval("ID") %>' Text='<%# "Details" %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField>
效果图:
八、选增删改
1、GridView自带的选中、编辑、删除,即CommandField
关键代码:
/// <summary> /// 在单击 GridView 控件内某一行的 Delete 按钮(其 CommandName 属性设置为"Delete"的按钮)时发生,但在 GridView 控件从数据源删除记录之前。此事件通常用于取消删除操作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string sqlStr = "delete from Employee where ID=" + Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value) + ""; Common.ExecuteSql(sqlStr); bind(); } /// <summary> /// 在单击 GridView 控件内某一行的 Update 按钮(其 CommandName 属性设置为"Update"的按钮)时发生,但在 GridView 控件更新记录之前。此事件通常用于取消更新操作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string ID = GridView1.DataKeys[e.RowIndex].Value.ToString(); string Emp_ID = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim(); string Emp_RealName = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim(); string Emp_Sex = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim(); string Emp_Address = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim(); string sqlStr = "update Employee set EmpID='" + Emp_ID + "',EmpRealName='" + Emp_RealName + "',EmpSex='" + Emp_Sex + "',EmpAddress='" + Emp_Address + "' where ID=" + ID + ""; Common.ExecuteSql(sqlStr); GridView1.EditIndex = -1; bind(); } /// <summary> /// 在单击 GridView 控件内某一行的 Edit 按钮(其 CommandName 属性设置为“Edit”的按钮)时发生,但在 GridView 控件进入编辑模式之前。此事件通常用于取消编辑操作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bind(); } /// <summary> /// 在单击 GridView 控件内某一行的 Cancel 按钮(其 CommandName 属性设置为“Cancel”的按钮)时发生,但在 GridView 控件退出编辑模式之前。此事件通常用于停止取消操作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bind(); }
效果图:
2、GridView添加记录,在GridView表脚添加控件,用添加记录
关键代码:
<asp:GridView ID="GridView1" ShowFooter="true" BorderColor="Black" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True"> <Columns> <asp:TemplateField HeaderText="账号"> <ControlStyle Width="100px" /> <ItemTemplate> <asp:Label ID="lbID" runat="server" Text='<%# Bind("EmpID") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtID" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="姓名"> <ControlStyle Width="100px" /> <ItemTemplate> <asp:Label ID="lbRealName" runat="server" Text='<%# Bind("EmpRealName") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtRealName" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="性别"> <ItemTemplate> <asp:Label ID="lbSex" runat="server" Text='<%# Bind("EmpSex") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:DropDownList ID="ddlSex" runat="server"> <asp:ListItem Value="男">男</asp:ListItem> <asp:ListItem Value="女">女</asp:ListItem> </asp:DropDownList> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="住址"> <ControlStyle Width="200px" /> <ItemTemplate> <asp:Label ID="lbAddress" runat="server" Text='<%# Bind("EmpAddress") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtAddress" runat="server" Width="80px"></asp:TextBox> <asp:Button ID="btnAdd" runat="server" Text="添 加" OnClick="btnAdd_Click" /> <asp:Button ID="btnCancel" runat="server" Text="取 消" OnClick="btnCancel_Click" /> </FooterTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView>
效果图:
3、更新所有记录,GridView直接绑定控件,然后更新
关键代码:
<asp:GridView ID="GridView1" BorderColor="Black" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" Font-Size="12px" Width="530px" AllowSorting="True"> <Columns> <asp:TemplateField HeaderText="账号"> <ControlStyle Width="100px" /> <ItemTemplate> <asp:TextBox ID="txtID" runat="server" Text='<%#Eval("EmpID") %>' ></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="姓名"> <ControlStyle Width="100px" /> <ItemTemplate> <asp:TextBox ID="txtRealName" runat="server" Text='<%#Eval("EmpRealName") %>'></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="性别"> <ItemTemplate> <asp:DropDownList ID="ddlSex" runat="server" /> <asp:HiddenField ID="hdfSex" runat="server" Value='<%# Eval("EmpSex") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="住址"> <ControlStyle Width="200px" /> <ItemTemplate> <asp:TextBox ID="txtAddress" runat="server" Width="80px" Text='<%#Bind("EmpAddress") %>'></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" /> <RowStyle HorizontalAlign="Center" /> <PagerStyle HorizontalAlign="Center" /> </asp:GridView>
效果图:
九、主键索引
根据主键多条记录删除,单条记录删除。
关键代码:
public void bind() { string sqlStr = "select * from Sms_Send"; DataSet myds = Common.dataSet(sqlStr); GridView1.DataSource = myds; GridView1.DataKeyNames = new string[] { "Mobile","SendTime" }; GridView1.DataBind(); }
/// <summary> /// 在单击 GridView 控件内某一行的 Delete 按钮(其 CommandName 属性设置为"Delete"的按钮)时发生,但在 GridView 控件从数据源删除记录之前。此事件通常用于取消删除操作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { int index = Convert.ToInt32(e.RowIndex);//get Row index DataKey datakey = GridView1.DataKeys[index]; string mobile = datakey["Mobile"].ToString(); string sendTime = datakey["SendTime"].ToString(); string sqlStr = "delete from Sms_Send where Mobile='" + mobile + "'and SendTime='" + sendTime + "'"; Common.ExecuteSql(sqlStr); bind(); }
效果图:
案例源代码下载地址:http://download.csdn.net/detail/lovegonghui/9263095
0 0
- GridView使用集合
- GridView使用集合
- GridView操作集合
- gridview集合splistitemcollection翻页
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- GridView问题集合
- Android GridView属性集合
- Android GridView属性集合 .
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Android GridView属性集合
- Linux增加静态路由方法
- spark-sql on yarn环境搭建
- IOS--自动布局 入门
- test——map
- Java学习笔记(五)接口及类
- GridView使用集合
- 哈夫曼树
- gitlab使用总结
- 论黑产黑阔如何安全地转移赃款/洗钱?
- L状态栏中的信号栏默认无上下行标识
- JAVA 实现Timestamp和String的相互转换
- F5+terracotta+EhCache配置分布式集群经验总结
- 关于WebRtc的一些个人理解
- Android 6.0新特性之Doze模式