1、控件的属性和方法
属性 |
描述 |
ClientID |
返回控件在浏览器端生成的标识符 |
Controls |
返回当前控件的子控件集合 |
EnableViewState |
返回或设置当前控件是否使用视图状态功能 |
ID |
返回或设置当前控件在页面中的唯一标识 |
Page |
返回当前页面的父页面引用 |
Parent |
返回当前控件父控件的引用,即其所在的容器控件 |
Visible |
返回或设置当前控件是否呈现在页面中 |
2、单选按钮与复选框
3、控制权转移控件
<h3>控制权转移控件</h3> <asp:Button ID="btn1" runat="server" Text="普通按钮" PostBackUrl="~/server.aspx" CommandArgument="hello" /> <asp:LinkButton ID="lbtn2" runat="server" Text="超链接按钮" PostBackUrl="~/server.aspx" CommandArgument="hello"/> <asp:ImageButton ID="imgbtn3" runat="server" ImageUrl="~/images/regist.gif" PostBackUrl="~/server.aspx" CommandArgument="hello" /> <br /> <%-- 仅仅是转换成普通的超链接a标签,不能提交 表单和跨页提交数据--%> <asp:HyperLink ID="hl1" runat="server" Text="普通超链接" NavigateUrl="~/server.aspx"/>
protected void Page_Load(object sender, EventArgs e) { txt.CssClass = "txt"; //txt.Text = DateTime.Now.ToString(); hl1.Target = "_blank"; }
四、FileUpload控件(实现文件的上传和下载)
<form id="form1" runat="server" enctype="multipart/form-data"> <div> 头像:<input type="file" name="uploadFile" /> <asp:Button ID="btnupload" runat="server" Text="上传文件" OnClick="btnupload_Click" /> </div> </form>
protected void btnupload_Click(object sender, EventArgs e) { //获得客户端上传的文件集合 HttpFileCollection files = Request.Files; //获得指定的文件对象 HttpPostedFile file = files[0]; if (file.FileName == "") { Response.Write("<script>alert('请选择文件上传');</script>"); return; } //if(file.ContentLength>10*1024) //{ // Response.Write("<script>alert('上传的文件不能超过10KB,请压缩后上传');</script>"); // return; //} //组装服务器端路径 string serverPath = "~/uploadFolder/" + file.FileName; serverPath = Server.MapPath(serverPath);//上传的路径必须是物理路径 file.SaveAs(serverPath);//实现上传 Response.Write("<script>alert('上传成功');</script>"); }
后端代码也可以为:
protected void btnupload_Click(object sender, EventArgs e) { if(!myFile.HasFile) { Response.Write("<script>alert('请选择文件上传');</script>"); return; } HttpPostedFile file = myFile.PostedFile; //if (file.ContentLength > 10 * 1024) //{ // Response.Write("<script>alert('上传的文件不能超过10KB,请压缩后上传');</script>"); // return; //} //组装服务器端路径 string serverPath = "~/uploadFolder/" + file.FileName; serverPath = Server.MapPath(serverPath);//上传的路径必须是物理路径 file.SaveAs(serverPath);//实现上传 Response.Write("<script>alert('上传成功');</script>"); }
批量上传文件代码:
<form id="form1" runat="server" enctype="multipart/form-data"> <div> <input type="button" name="btnaddFile" value="点击上传" id="btnaddFile" /> <asp:Button ID="btnuploadFile" runat="server" Text="批量上传" OnClick="btnuploadFile_Click" /> </div> <div id="files"> </div> </form> <script src="scripts/jquery.js"></script> <script> $(function () { var i = 1; $("#btnaddFile").click(function () { var file = $("<input type='file' class='file' name='file" + i + "'/><br/>"); $("#files").append(file); i++; }) }) </script>
protected void btnuploadFile_Click(object sender, EventArgs e) { if (Request.Files.Count == 0) return; int count = 0; for(int i = 0; i < Request.Files.Count; i++) { HttpPostedFile file = Request.Files[i]; string name = file.FileName; if(name!="") { string path = "~/uploadFolder/" + name; path = Server.MapPath(path); file.SaveAs(path); count++; } } Response.Write("<script>alert('成功上传" + count + "个文件')</script>"); }
5、下载文件
<form id="form1" runat="server"> <div> <asp:HyperLink ID="hlDownLoad" runat="server" Text="点击下载"/><br /> <asp:Button ID="btnDownLoad" runat="server" Text="点击下载" OnClick="btnDownLoad_Click"/> </div> </form>
protected void Page_Load(object sender, EventArgs e) { //下载时提代文件的虚拟路径或相对路径 //hlDownLoad.NavigateUrl = "~/uploadFolder/逻辑题.doc"; //hlDownLoad.Text = "逻辑题.doc"; //hlDownLoad.NavigateUrl = "~/uploadFolder/test.xlsx"; //hlDownLoad.Text = "test.xlsx"; //hlDownLoad.NavigateUrl = "~/uploadFolder/test.txt"; //hlDownLoad.Text = "test.txt"; hlDownLoad.NavigateUrl = "~/uploadFolder/book.jpg"; hlDownLoad.Text = "book.jpg"; } protected void btnDownLoad_Click(object sender, EventArgs e) { string fileName = "book.jpg"; string path = "~/uploadFolder/" + fileName; path = Server.MapPath(path); byte[] bytes = null; using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { //创建字节数组缓冲区 bytes= new byte[fs.Length]; //读取文件到字节数组中 fs.Read(bytes, 0, bytes.Length); } //通知浏览器文件是以附件形式下载,而不是直接打开的 Response.AddHeader("Content-Disposition", "attachment;Filename="+fileName); //将缓冲区的字节数组下载到本地 Response.BinaryWrite(bytes); //停止当前页的执行 Response.End(); }
6、droplist和listbox控件
<form id="form1" runat="server"> <div> 班级:<asp:DropDownList ID="drpClass" runat="server" OnSelectedIndexChanged="drpClass_SelectedIndexChanged" Width="150"> </asp:DropDownList> <br /> 学员:<asp:ListBox ID="lstStudents" runat="server" Width="150" SelectionMode="Multiple"> </asp:ListBox> </div> </form> <script src="scripts/jquery.js"></script> <script> $(function () { $("#drpClass").change(function () { var cno=$(this).val();//班级编号 if (cno != "-99") $("#form1").submit();//手动提交表单 else $("#lstStudents").get(0).options.length = 0; //清空下拉列表 }) }) </script>
private void LoadClass() { List<@class> lstClass = db.@class.ToList(); lstClass.Insert(0,new @class { className = "--请选择班级--", classNo = "-99" }); #region 方法1:使用Items属性 //foreach (var c in lstClass) //{ // ListItem item = new ListItem { Text = c.className, Value = c.classNo }; // drpClass.Items.Add(item); //} #endregion #region 方法2:使用DataSource属性 drpClass.DataSource = lstClass;//设置数据源 drpClass.DataTextField = "className";//显示的属性是数据源中的哪个字段或属性 drpClass.DataValueField = "classNo";//隐藏的属性是数据源中的哪个字段或属性 drpClass.DataBind();//将当前控件的数据绑定至控件中,一定要调用 #endregion } /// <summary> /// 班级下拉列表选项改变时触发 /// </summary> protected void drpClass_SelectedIndexChanged(object sender, EventArgs e) { string cno = drpClass.SelectedValue;//获取当前选中班级的班级编号 LoadStudents(cno); } /// <summary> /// 根据班级编号加载学员 /// </summary> /// <param name="cno">班级编号</param> private void LoadStudents(string cno) { List<student> lststus = db.student.Where(s => s.classNo == cno).ToList(); lstStudents.DataSource = lststus; lstStudents.DataTextField = "sname"; lstStudents.DataValueField = "sno"; lstStudents.DataBind(); }
7.验证控件
<form id="form1" runat="server"> <div> <div> <label>用户名:</label> <asp:TextBox ID="txtUserName" runat="server" /> <asp:RequiredFieldValidator ID="userNameRequiredValidator" runat="server" ErrorMessage="用户名不能为空" ControlToValidate="txtUserName" SetFocusOnError="True" Display="None" /> </div> <div> <label>密码:</label> <asp:TextBox ID="txtPwd" runat="server" /> <asp:RequiredFieldValidator ID="pwdRequiredValidator" runat="server" ErrorMessage="密码不能为空" ControlToValidate="txtPwd" SetFocusOnError="True" Display="None" /> </div> <div> <label>确认密码:</label> <asp:TextBox ID="txtPwdConfirm" runat="server" /> <asp:RequiredFieldValidator ID="pwdConfirmRequiedValidator" runat="server" ErrorMessage="确认密码不能为空" ControlToValidate="txtPwdConfirm" SetFocusOnError="True" Display="Dynamic" /> <asp:CompareValidator ID="pwdComapreValidator" runat="server" ErrorMessage="两次密码不一致" ControlToCompare="txtPwd" ControlToValidate="txtPwdConfirm" Display="Dynamic" /> </div> <div> <label>出生日期:</label> <asp:TextBox ID="txtBirth" runat="server" /> <asp:CompareValidator ID="birthCompareValidator" runat="server" ErrorMessage="出生日期有误" ControlToValidate="txtBirth" Display="Dynamic" Operator="LessThan" Type="Date" /> </div> <div> <label>工作年限:</label> <asp:TextBox ID="txtWorkYears" runat="server" /> <asp:RangeValidator ID="workYearsRangeValidator" runat="server" ErrorMessage="工作年限必须在3-10年" ControlToValidate="txtWorkYears" MaximumValue="10" MinimumValue="3" SetFocusOnError="True" Type="Double" /> </div> <div> <label>工作邮箱:</label> <asp:TextBox ID="txtEmail" runat="server" /> <asp:RegularExpressionValidator ID="emailRegularValiator" runat="server" ErrorMessage="电子邮箱不正确" SetFocusOnError="true" ValidationExpression="w+@w+.w+" ControlToValidate="txtEmail" /> </div> <div> <label>掌握技能:</label> <asp:CheckBox ID="chk1" runat="server" Text="C#" /> <asp:CheckBox ID="chk2" runat="server" Text="SQL Server" /> <asp:CheckBox ID="chk3" runat="server" Text="javascript" /> <asp:CheckBox ID="chk4" runat="server" Text="asp.net" /> <asp:CustomValidator ID="skillValidator" runat="server" ErrorMessage="至少掌握两项技能" OnServerValidate="skillValidator_ServerValidate" ClientValidationFunction="checkSkill" /> </div> <div> <asp:Button ID="btnsubmit" runat="server" Text="注册" OnClick="btnsubmit_Click" ValidationGroup="A" /> </div> </div> <div> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false"/> </div> </form>
protected void Page_Load(object sender, EventArgs e) { //设置出生日期比较验证控件要比较的值是当前系统日期 birthCompareValidator.ValueToCompare = DateTime.Now.ToShortDateString(); } /// <summary> /// 强制重新验证 /// </summary> //public override void Validate() //{ // if (txtUserName.Text.Length < 6) // userNameRequiredValidator.IsValid = false; //} protected void btnsubmit_Click(object sender, EventArgs e) { if (IsValid) Response.Write("ok"); } protected void skillValidator_ServerValidate(object source, ServerValidateEventArgs args) { int count = 0; if (chk1.Checked) count++; if (chk2.Checked) count++; if (chk3.Checked) count++; if (chk4.Checked) count++; if (count < 2) { args.IsValid = false; } }
8.简单绑定
示例1:
<form id="form1" runat="server"> <div> <div> 姓名:<asp:TextBox ID="txtname" runat="server" Text="<%#name%>" /><br /> 年龄:<%=age%><br /> 头像:<asp:Image ID="imgFace" runat="server" ImageUrl="<%#path%>" /><br /> </div> <div> <% for(int i=0;i<10;i++) { Response.Write(i + "<br>"); } %> </div> </div> </form>
public string name = "张三"; public string path = "~/images/1.gif"; public int age = 20; protected void Page_Load(object sender, EventArgs e) { //this:aspx文件形成的类 //Response.Write(this.GetType().ToString()+"<br/>"); //Response.Write(this.GetType().BaseType.ToString()); this.DataBind(); }
示例2:
<form id="form1" runat="server"> <div> <table border="1" style="1000px"> <tr> <td colspan="3" style="text-align:center"><h3>人气投票</h3></td> </tr> <tr> <td class="auto-style1">张三</td> <td class="auto-style2"> <asp:Label ID="lblZS" runat="server" BackColor="Yellow" Text="<%#zs%>" Width="<%#zs*10 %>" /> <%#GetPercent(zs)%> </td> <td> <asp:Button ID="btnZS" runat="server" Text="投票" OnClick="btnZS_Click" /> </td> </tr> <tr> <td class="auto-style1">李四</td> <td class="auto-style2"> <asp:Label ID="lblLS" runat="server" BackColor="Green" Text="<%#ls%>" Width="<%#ls*10 %>" /> <%#GetPercent(ls)%> </td> <td> <asp:Button ID="btnLS" runat="server" Text="投票" OnClick="btnLS_Click"/> </td> </tr> <tr> <td class="auto-style1">王五</td> <td class="auto-style2"> <asp:Label ID="lblWW" runat="server" BackColor="YellowGreen" Text="<%#ww%>" Width="<%#ww*10 %>" /> <%#GetPercent(ww)%> </td> <td> <asp:Button ID="btnWW" runat="server" Text="投票" OnClick="btnWW_Click" /> </td> </tr> </table> </div> </form>
public static int zs = 0; public static int ls = 0; public static int ww = 0; protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) this.DataBind(); } protected void btnZS_Click(object sender, EventArgs e) { zs++; this.DataBind(); } protected void btnLS_Click(object sender, EventArgs e) { ls++; this.DataBind(); } protected void btnWW_Click(object sender, EventArgs e) { ww++; this.DataBind(); } /// <summary> /// 计算百分比 /// </summary> /// <param name="num"></param> /// <returns></returns> public string GetPercent(double num) { if (num == 0) return "0.00%"; double sum = zs + ls + ww; double rate = num*100 / sum; return rate.ToString("n2") + "%"; }
9.GridView数据绑定控件
列的类型
BoundField 设置DataField="要绑定数据源中的字段"
HypterLinkField 设置DataTextField="要显示的是数据源中的哪个字段"
DataNavigateUrlFormatString="要跳转的页面路径"
DataNavigateUrlFields="页面路径中查询字符串的值是哪个属性"
CheckBoxField 设置DataField="要绑定数据源中的布尔类型的字段"
ImageField 设置DataImageUrlField="要绑定数据源中的图片路径的字段"
ButtonField 显示按钮 ,可以设置CommandName,用以指定按钮的用途
CommandField 显示指定的操作,如删除,编辑
TemplateField 模板列,用于自定义显示数据
HeaderTemplate:头部模板 显示提示信息
FooterTemplate:脚注模板 显示汇总信息 设置GridView ShowFooter="true"
ItemTemplate:项目模板 绑定数据源中要显示的属性或字段 <%#Bind("字段")%>
AlternatingItemTemplate:交替项模板
EditItemTemplate:编辑模板
示例1:
<form id="form1" runat="server"> <div> <asp:GridView ID="gvStudents" runat="server" AutoGenerateColumns="false" OnRowDeleting="gvStudents_RowDeleting"> <Columns> <asp:BoundField HeaderText="学号" DataField="sno" /> <asp:HyperLinkField HeaderText="姓名" DataTextField="sname" DataNavigateUrlFormatString="~/details.aspx?no={0}" DataNavigateUrlFields="sno" /> <asp:CheckBoxField HeaderText="性别" DataField="sex" /> <asp:BoundField HeaderText="邮箱" DataField="semail" /> <asp:BoundField HeaderText="地址" DataField="saddress" /> <asp:BoundField HeaderText="出生日期" DataField="sbirthday" DataFormatString="{0:yyyy-MM-dd}" /> <asp:ImageField HeaderText="头像" DataImageUrlField="faceUrl" /> <asp:ButtonField HeaderText="" Text="删除" ButtonType="Button" CommandName="delete"/> <asp:CommandField HeaderText="操作" ShowDeleteButton="true" ShowEditButton="true" ShowSelectButton="true" ButtonType="Button" /> </Columns> </asp:GridView> </div> </form>
StuDBDataContext db = new StuDBDataContext(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) LoadStudents(); } private void LoadStudents() { List<student> lstStudents = db.student.ToList(); foreach (var item in lstStudents) { item.faceUrl = "~/images/" + item.faceUrl; } gvStudents.DataSource = lstStudents; this.DataBind(); } protected void gvStudents_RowDeleting(object sender, GridViewDeleteEventArgs e) { Response.Write("删除成功"); }
示例2:
<form id="form1" runat="server"> <div> <asp:GridView ID="gvStudents" runat="server" AutoGenerateColumns="false" ShowFooter="true"> <Columns> <%-- 学号--%> <asp:TemplateField> <HeaderTemplate>学号</HeaderTemplate> <%-- <FooterTemplate> <asp:TextBox ID="txt" runat="server" /> </FooterTemplate>--%> <ItemTemplate> <asp:Label ID="lblsno" runat="server" Text='<%#Bind("sno") %>' /> </ItemTemplate> <%-- <AlternatingItemTemplate> <asp:TextBox ID="txtsno" runat="server" Text='<%#Bind("sno") %>' /> </AlternatingItemTemplate>--%> <EditItemTemplate> <asp:TextBox ID="txtsno" runat="server" Text='<%#Bind("sno") %>' /> </EditItemTemplate> </asp:TemplateField> <%-- 姓名--%> <asp:TemplateField HeaderText="姓名"> <ItemTemplate> <asp:Label ID="lblsname" runat="server" Text='<%#Eval("sname") %>' /> <%--<asp:HyperLink ID="hlsname" runat="server" NavigateUrl="~/details.aspx" Text='<%#Eval("sname") %>' />--%> </ItemTemplate> </asp:TemplateField> <%-- 性别--%> <asp:TemplateField HeaderText="性别"> <ItemTemplate> <asp:Label ID="lblsex" runat="server" Text='<%#(bool)Eval("sex")?"男":"女"%>' /> </ItemTemplate> </asp:TemplateField> <%--邮箱--%> <asp:TemplateField HeaderText="邮箱"> <ItemTemplate> <asp:Label ID="lblsemail" runat="server" Text='<%#Eval("semail") %>' /> </ItemTemplate> </asp:TemplateField> <%--家庭地址--%> <asp:TemplateField HeaderText="家庭地址"> <ItemTemplate> <asp:Label ID="lblsaddress" runat="server" Text='<%#Eval("saddress") %>' /> </ItemTemplate> </asp:TemplateField> <%--出生日期--%> <asp:TemplateField HeaderText="出生日期"> <ItemTemplate> <asp:Label ID="lblsbirthday" runat="server" Text='<%#((DateTime)Eval("sbirthday")).ToShortDateString() %>' /> </ItemTemplate> </asp:TemplateField> <%--头像--%> <asp:TemplateField HeaderText="头像"> <ItemTemplate> <asp:Image ID="imgface" runat="server" ImageUrl='<%#Eval("faceUrl") %>' /> </ItemTemplate> </asp:TemplateField> <%--操作--%> <asp:TemplateField HeaderText="头像"> <ItemTemplate> <asp:Button ID="btndelete" runat="server" Text="删除" CommandName="delete" /> <asp:LinkButton ID="btnedit" runat="server" Text="编辑" CommandName="edit"/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form>
StuDBDataContext db = new StuDBDataContext(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) LoadStudents(); } private void LoadStudents() { List<student> lstStudents = db.student.ToList(); foreach (var item in lstStudents) { item.faceUrl = "~/images/" + item.faceUrl; } gvStudents.DataSource = lstStudents; this.DataBind(); }
示例3:
<form id="form1" runat="server"> <div id="divdata"> <asp:GridView ID="gvStudents" runat="server" DataKeyNames="sno" AutoGenerateColumns="false" OnRowDeleting="gvStudents_RowDeleting" OnRowEditing="gvStudents_RowEditing" OnRowCancelingEdit="gvStudents_RowCancelingEdit" OnRowDataBound="gvStudents_RowDataBound" OnRowUpdating="gvStudents_RowUpdating" AllowPaging="true" PageSize="3" OnPageIndexChanging="gvStudents_PageIndexChanging" OnSelectedIndexChanging="gvStudents_SelectedIndexChanging"> <Columns> <%-- 复选框--%> <asp:TemplateField> <HeaderTemplate> <input type="checkbox" id="chkAll" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chkDelete" runat="server"/> </ItemTemplate> </asp:TemplateField> <%--学号--%> <asp:TemplateField HeaderText="学号"> <ItemTemplate> <asp:Label ID="lblsno" runat="server" Text='<%#Bind("sno") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtsno" runat="server" Text='<%#Bind("sno") %>' ReadOnly="true" /> </EditItemTemplate> </asp:TemplateField> <%-- 姓名--%> <asp:TemplateField HeaderText="姓名"> <ItemTemplate> <asp:Label ID="lblsname" runat="server" Text='<%#Eval("sname") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtsname" runat="server" Text='<%#Bind("sname") %>' /> </EditItemTemplate> </asp:TemplateField> <%-- 性别--%> <asp:TemplateField HeaderText="性别"> <ItemTemplate> <asp:Label ID="lblsex" runat="server" Text='<%#(bool)Eval("sex")?"男":"女"%>' /> </ItemTemplate> <EditItemTemplate> <asp:DropDownList ID="drpSex" runat="server"> <asp:ListItem Value="-1">--请选择--</asp:ListItem> <asp:ListItem Value="1">男</asp:ListItem> <asp:ListItem Value="0">女</asp:ListItem> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField> <%--邮箱--%> <asp:TemplateField HeaderText="邮箱"> <ItemTemplate> <asp:Label ID="lblsemail" runat="server" Text='<%#Eval("semail") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtsemail" runat="server" Text='<%#Bind("semail") %>' /> </EditItemTemplate> </asp:TemplateField> <%--家庭地址--%> <asp:TemplateField HeaderText="家庭地址"> <ItemTemplate> <asp:Label ID="lblsaddress" runat="server" Text='<%#Eval("saddress") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtsaddress" runat="server" Text='<%#Bind("saddress") %>' /> </EditItemTemplate> </asp:TemplateField> <%--出生日期--%> <asp:TemplateField HeaderText="出生日期"> <ItemTemplate> <asp:Label ID="lblsbirthday" runat="server" Text='<%#((DateTime)Eval("sbirthday")).ToShortDateString() %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtsbirthday" runat="server" Text='<%#Bind("sbirthday") %>' /> </EditItemTemplate> </asp:TemplateField> <%--头像--%> <asp:TemplateField HeaderText="头像"> <ItemTemplate> <asp:Image ID="imgface" runat="server" ImageUrl='<%#Eval("faceUrl") %>' /> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtface" runat="server" Text='<%#Bind("faceUrl") %>' /> </EditItemTemplate> </asp:TemplateField> <%--操作--%> <asp:TemplateField HeaderText="头像"> <ItemTemplate> <asp:Button ID="btndelete" runat="server" Text="删除" CommandName="delete" /> <asp:Button ID="btnedit" runat="server" Text="编辑" CommandName="edit"/> <asp:Button ID="btnselect" runat="server" Text="选择" CommandName="select" /> </ItemTemplate> <EditItemTemplate> <asp:Button ID="btnupdate" runat="server" Text="更新" CommandName="update" /> <asp:Button ID="btncancel" runat="server" Text="取消" CommandName="cancel" /> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button ID="btnDeleteAll" runat="server" Text="全部删除" OnClick="btnDeleteAll_Click" /> <asp:TextBox ID="txtsnos" runat="server" Width="300"/> </div> </form> <script src="scripts/jquery.js"></script> <script> $(function () { $("#txtsnos").css("display", "none"); //设置表格的样式 $("#gvStudents tbody tr:eq(0)").css({ "height": "30px","background":"pink" }); $("#gvStudents tbody tr:gt(0):odd").css("background", "lightblue"); $("#gvStudents tbody tr:gt(0):even").css("background", "#ccc"); var oldbg; $("#gvStudents tbody tr:gt(0)").mouseover(function () { oldbg = $(this).css("background"); $(this).css("background", "yellow"); }).mouseout(function () { $(this).css("background", oldbg); }) //全选 $("#chkAll").click(function () { var state=$(this).prop("checked"); $(":checkbox[id*=chkDelete]").each(function (i, chk) { //$(chk).prop("checked", state); //如果当前复选框的状态和全选复选框的状态不一致,就做点击 if ($(chk).prop("checked") != state) $(chk).click(); }) }) //反选 $(":checkbox[id*=chkDelete]").click(function () { var flag = $(":checkbox[id*=chkDelete]").length == $(":checkbox[id*=chkDelete]:checked").length; $("#chkAll").prop("checked", flag); var sno=$(this).parent().next().children("span").html();//获得当前复选框的父元素td的下一个兄弟元素td的子元素span中的html代码 //点击每一行前面的复选框时 //判断当前复选框点击是选中状态还是取消选中状态 if ($(this).prop("checked")) { $("#txtsnos").val($("#txtsnos").val()+sno+";");//如果选中,则将当前的学号保存至文本框中 } else { $("#txtsnos").val($("#txtsnos").val().replace(sno + ";", ""));//如果是取消选中,则从文本框中删除学号 } }) //删除 $(":input[id*=btndelete]").click(function () { if (!confirm("确定要删除吗?")) return false; }) //全部删除 $("#btnDeleteAll").click(function () { if (!confirm("确定要删除选中的学员吗?")) return false; }) }) </script>
StuDBDataContext db = new StuDBDataContext(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) LoadStudents(); } private void LoadStudents() { List<student> lstStudents = db.student.ToList(); foreach (var item in lstStudents) { item.faceUrl = "~/images/" + item.faceUrl; } gvStudents.DataSource = lstStudents; this.DataBind(); } //删除 protected void gvStudents_RowDeleting(object sender, GridViewDeleteEventArgs e) { int deleteState = 0; try { string sno = gvStudents.DataKeys[e.RowIndex].Value.ToString();//学号 student stu = db.student.FirstOrDefault(s => s.sno == sno); db.student.DeleteOnSubmit(stu); db.SubmitChanges(); deleteState = 1; } catch (Exception ex) { throw ex; } if (deleteState == 1) { LoadStudents(); Response.Write("<script>alert('删除成功');</script>"); } else Response.Write("<script>alert('删除失败');</script>"); } //编辑 protected void gvStudents_RowEditing(object sender, GridViewEditEventArgs e) { gvStudents.EditIndex = e.NewEditIndex;//设置要编辑的这行的索引就是当前点前的这行的索引 LoadStudents(); } //取消 protected void gvStudents_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gvStudents.EditIndex = -1; LoadStudents(); } //更新 protected void gvStudents_RowUpdating(object sender, GridViewUpdateEventArgs e) { int index = e.RowIndex; GridViewRow row = gvStudents.Rows[index]; string sno = gvStudents.DataKeys[e.RowIndex].Value.ToString(); string sname = ((TextBox)row.FindControl("txtsname")).Text; bool sex = ((DropDownList)row.FindControl("drpSex")).SelectedValue == "1" ? true : false; string semail = ((TextBox)row.FindControl("txtsemail")).Text; string saddress = ((TextBox)row.FindControl("txtsaddress")).Text; DateTime sbirthday = Convert.ToDateTime(((TextBox)row.FindControl("txtsbirthday")).Text); string faceUrl = ((TextBox)row.FindControl("txtface")).Text; int modifyState = 0; try { student stu = db.student.FirstOrDefault(s => s.sno == sno); stu.sno = sno; stu.sname = sname; stu.sex = sex; stu.semail = semail; stu.saddress = saddress; stu.sbirthday = sbirthday; stu.faceUrl = faceUrl.Substring(faceUrl.LastIndexOf("/") + 1); db.SubmitChanges(); modifyState = 1; } catch (Exception ex) { Response.Write(ex.Message); } if (modifyState == 1) { gvStudents.EditIndex = -1;//取消编辑 LoadStudents();//重新绑定数据 Response.Write("<script>alert('更新成功');</script>"); } else Response.Write("<script>alert('更新失败');</script>"); } //在绑定每一行时触发 protected void gvStudents_RowDataBound(object sender, GridViewRowEventArgs e) { //Response.Write("当前行的下标:" + e.Row.RowIndex+"<br/>"); //Response.Write("当前行的类型:" + e.Row.RowType.ToString() + "<br/>"); //Response.Write("当前行的状态:" + e.Row.RowState.ToString() + "<br/>"); string sex = "";//保存当前正在绑定的学员的性别 if (e.Row.RowType == DataControlRowType.DataRow) { string sno = gvStudents.DataKeys[e.Row.RowIndex].Value.ToString(); //获得性别 student stu = db.student.FirstOrDefault(s => s.sno == sno); sex = (bool)stu.sex ? "1" : "0"; //判断当前正在绑定的这行学号在不在文本框 if(txtsnos.Text.Contains(sno)) { //获得当前这行正在绑定的复选框对象 CheckBox chk = e.Row.FindControl("chkDelete") as CheckBox; //设置它的状态为选中状态 chk.Checked = true; } } //普通项处于编辑状态,交替项的编辑状态 if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate)) { DropDownList drpSex = e.Row.FindControl("drpSex") as DropDownList; if (drpSex != null) drpSex.SelectedValue = sex;//设置性别下拉列表的选中状态是当前学员的性别 TextBox txtsno = (TextBox)e.Row.FindControl("txtsno"); txtsno.Width = 80; } } //分页 protected void gvStudents_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvStudents.PageIndex = e.NewPageIndex;//设置页码下标 LoadStudents(); } //全部删除 protected void btnDeleteAll_Click(object sender, EventArgs e) { string snos = txtsnos.Text; string[] snoArr = snos.Split(';'); for(int i = 0; i < snoArr.Length - 1; i++) { string sno = snoArr[i]; //student stu = db.student.FirstOrDefault(s => s.sno == sno); //db.student.DeleteOnSubmit(stu); //db.SubmitChanges(); } LoadStudents(); } //选中某行时 protected void gvStudents_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { int index = e.NewSelectedIndex; string sno = gvStudents.DataKeys[index].Value.ToString(); Response.Redirect("~/details.aspx/no=" +Server.UrlEncode(sno) + ""); }