.Net webform笔记

NET 笔记

一.html与一般处理程序(.aspx)的连接

(一)html页

<!DOCTYPE html>
<html>
<head>
    
    <meta charset="utf-8"/>
    <title></title>
</head>
<body>
    <form action="/Handler1.ashx" method="post">
        账号:<input type="text" name="uname"  /><br />    
        密码:<input type="password" name="upwd" value="" />
        <input type="submit" name="name" value="登录" />
    </form>
    
</body>
</html>
action处理  method方法 

(二)一般处理程序(.aspx)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
​
namespace WebApplication2
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {
​
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //1.获取前台的Request并解析
            string account = context.Request.Params["uname"];
            string pwd = context.Request.Params["upwd"];
​
            //2.模拟数据库操作
            if (account == "123" && pwd == "admin")
            {
                context.Response.Write("登录成功");
            }
            else
            {
                context.Response.Write("登录失败");
            }
​
            //context.Response.Write("Hello World");
        }
​
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
​
Response反应   Contentype内容类型  Params参数

IsPostBack 是不是会发 true:是回发 false:首次加载

二.跨页面数据传输(web窗体之间传输)

web窗体1进行设计 在按钮那加PostBackUrl="指向的页面"

web窗体2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
​
namespace WebApplication6._16
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (PreviousPage != null)
            {
                TextBox t1 = (TextBox)PreviousPage.FindControl("TextBox1");
                //t1.Text  //账号
                TextBox t2 = (TextBox)PreviousPage.FindControl("TextBox2");
                if (t1.Text == "1" && t2.Text == "a")
                {
                    Response.Write("登陆成功");
                }
                else
                {
                    Response.Write("登录失败");
                }
          
        }
​
    }
    }
}
PreviousPage上一页(是否有指向的页面) FindControl控件

三.页内传值

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewState.aspx.cs" Inherits="ViewState.ViewState" %>
​
<!DOCTYPE html>
​
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            单身<asp:Literal ID="lit" runat="server">0</asp:Literal>年
         
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="+1" />
        </div>
    </form>
</body>
</html>
​
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
​
namespace ViewState
{
    public partial class ViewState : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //设置初始值
            //1.首次加载
            if (!IsPostBack)
            {//            key      value
                ViewState["c"] = 0;
            }
        }
        //没有成员变量
        //无状态:
        
        protected void Button1_Click(object sender, EventArgs e)
        {
            
            int counter = (int)ViewState["c"];
            counter++;
            lit.Text = counter.ToString();
            ViewState["c"] = counter;
        }
    }
}

效果如下:

单身0+1 每次按+1的时候加1

页面对象

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="_02页面对象复习.WebForm1" %>
​
<!DOCTYPE html>
​
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            姓名:<asp:TextBox ID="box1" runat="server"></asp:TextBox><br />
            <asp:RadioButton ID="rbtn1" Checked="true" GroupName ="gender" runat="server" Text="男" />
            <asp:RadioButton ID="rbtn2" GroupName="gender" runat="server" Text="女" /><br />
            <asp:Button ID="Button1" runat="server" Text="提交" OnClick="Button1_Click" />
​
        </div>
    </form>
</body>
</html>
​
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
​
namespace _02页面对象复习
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
​
        }
​
        protected void Button1_Click(object sender, EventArgs e)
        {
            string name = box1.Text;
            string gender = "先生";
            if (rbtn2.Checked)
            {
                gender = "女士";
            }
​
            //重定向
            Response.Redirect($"newPage.aspx?姓名={name}&性别={gender}");
        }
    }
}

基本控件

文本型控件:

Literal控件:纯文本,不生成任何多于代码(推荐使用)

TextBox控件:在页面上显示一个可编辑的文本框

常用属性: ReadOnly:获取或设置一个值,用于指示能否更改TextBox控件的内容 TextMode:获取或设置TextBox控件的行为模式 SingleLine:单行 MultiLine:多行 Password:密码(*)

按钮类型控件:

Button

常用属性:PostBackUrl(跨页提交)、 CommadName(按钮相关的命令名)、 CausesValidation:是否激活验证、 OnclientClick:引发Button控件的Click事件时所执行的客户端脚本 LinkButton ImageButton

HyperLink

功能上与HTML的超链接一致,但是可以在后台动态

改变,通过:NavigateUrl属性

Text一段简短的描述性文本,用于指定链接的用途
Target链接的目标窗口/框架。
NavigateUrl单击链接时用户即将链接到的页面网址或URL Redirect
ImageUrl指定用于链接的图像URL

ListBox(文本型下拉框)

属性说明
Items获取列表控件项的集合
SelectionModeSingle Multiple
SelectedIndex获取或设置列表控件中选定项的最低序号索引
SelectedItem获取列表控件中选定项的最低序号索引
SelectedValue获取列表控件中选定项的值,或选择列表控件中包含指定值的项
Rows获取或设置ListBox控件中显示的行数
DataSource获取或设置对象,数据绑定控件从该对象中检索其数据项列表
ID获取或设置分配给服务器控件的编程标识符

DropDownList(下拉框)

AutoPostBack 动态显示:**True**选择一个列表项时DropDownList控件状态是否发回到服务器的值(True/False)
DataMember获取或设置数据源中的特定表格以绑定到该控件
DataSource DataBind()获取或设置填充列表控件的组成项的数据源
DataTextField获取或设置提供列表项文本内容的数源的字段
DataTextFormatString获取或设置用于控制如何显示绑定到列表控件的数据的格式字符串
DataValueField获取或设置提供列表项文本内容的数据源的字段
Items获取或者设置选项的值
事 件说 明
SelectedIndexChanged当从列表控件选择的内容在发布到服务器的操作之间发生变化时发生

RadioButton(用于单选)

属 性说 明
AutoPostBack当选定内容更改后,自动回发到服务器
RepeatDirection获取或设置在RadioButtonList控件了子选项的排列方向
RepeatColumns获取或设置要在RadioButtonList控件中显示的列数
RepeatLayout获取或设置单选按钮的布局
Items列表中项的集合
GoupNome获取或设置单选按钮的布局(定义为一个类)
TextAlign获取或设置与控件相关联文本的对齐方式

CheckBox

属 性说 明
AutoPostBack当选定内容更改后,自动回发到服务器
RepeatColumns获取或设置CheckBoxList中显示的列数
RepeatDirection获取或设置CheckBoxList中各个选项的排列顺序
Items列表中项的集合
TextAlign获取或设置与CheckBoxList关联文本的对齐方式

ListBox例题:

上下移

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page.aspx.cs" Inherits="_05基本控件.ListBox.Page" %>
​
<!DOCTYPE html>
​
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ListBox ID="list1" runat="server" Height="112px" SelectionMode="Multiple" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
                
            </asp:ListBox>
            <br />
            <asp:Button ID="Button3" runat="server" Text="全部下移" OnClick="Button3_Click" />
&nbsp;<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="全部上移" />
&nbsp;<asp:Button ID="Button2" runat="server" Text="选中下移" OnClick="Button2_Click" />
&nbsp;<asp:Button ID="Button4" runat="server" Text="选中上移" />
            <br />
            <asp:ListBox ID="list2" runat="server" Height="112px" SelectionMode="Multiple"></asp:ListBox>
        </div>
    </form>
</body>
</html>
​
​
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _05基本控件.ListBox
{
    public partial class Page : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //集合
                ArrayList list = new ArrayList();
                list.Add("周一");
                list.Add("周二");
                //导入数据
                list1.DataSource = list;
                //数据更新
                list1.DataBind();

                //3.
                list1.Items.Add("周三");
                list1.Items.Add("周四");
                list1.Items.Add("周五");
                list1.Items.Add("周六");
                list1.Items.Add("周天");

            }
        }

        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write("下标"+list1.SelectedIndex);
            Response.Write("Value" + list1.SelectedValue);
            Response.Write("Item" + list1.SelectedItem);
        }

        //全部下移
        protected void Button3_Click(object sender, EventArgs e)
        {
            //集合个数  count
            int count = list1.Items.Count;
            for(int i = 0; i<count; i++)
            {
                //获取元素
                ListItem item = list1.Items[0];

                list2.Items.Add(item);
                list1.Items.Remove(item);
            }
        }

        //选中下移
        protected void Button2_Click(object sender, EventArgs e)
        {
            //
            int count = list1.Items.Count;

            int index = 0;
            for (int i = 0; i< count; i++)
            {
                ListItem obj = list1.Items[index];
                if (obj.Selected)
                {
                   
                    //int index = list1.SelectedIndex;

                    list2.Items.Add(obj);
                    list1.Items.Remove(obj);

                    index--;
                }
                index++;
            }
        }
    }
}
DataSource数据源 Databind数据绑定

Session对象

ViewState对象无法实现不同页面之间的数据交换

Sesion(会话)对象 实现不同页面之间的数据交换

与ViewState一样是“键--值”对存取数据

设置有效期:DateTime.Now.AddDays(1.0) --一天 AddMinutes(1.0) -- 一分钟

ViewState["Key"]: = Value 保存状态

Request: QueryString, Params

Response: Redirect:重定向

Session["Key"] = Value;

Server: Execute, Transfer

compareValidator 比较验证

ContrlToCompare指定用来比较值的控件的ID
ContrlToValidate指定将要验证的控件的ID
ErrorMessage在页面中使用ValidationSummary控件时显示错误消息
Text用于指定验证控件后出现错误时将会显示的错误信息
ValueToCompare指定与所验证控件中的值相比较的值
方 法说 明
Validate执行验证,它将根据验证的成功情况将IsValid属性更改为True或False
Operator执行的操作类型

控件C#一定要加不然就会报错

  protected void Page_Load(object sender, EventArgs e)
        {
            UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
        }

rangeValidator范围验证

属 性说 明
ControlToValidate指定将要检查其值的控件,它具有该控件的ID值
ErrorMessage指定在页面中使用ValidationSummary控件时该控件中显示的错误消息
MaximumValue指定容许为此控件设置的最大值
MinimumValue指定容许为此控件设置的最小值
Type设置控件所验证的数据类型

requiredfieldvalidator 必填验证(非空)

ControlToValidate用于指定将要检查其值的控件,它具有该控件的ID值
ErrorMessage用于指定在窗体中同时使用ValidationSummary控件与RequierdFieldValidator控件时前者中显示的错误信息。如果未设置文本属性,则此属性将用于显示窗体中的错误
ForeColor错误提示文字颜色
方 法说 明
Validate此方法用于执行验证。它将根据验证的成功情况将IsValid属性更改为True或False

RegularExpressionValidator 用于邮箱验证

ValidationExpression[验证表达式]

连接数据库

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebApplication6._16.DDSC
{
    public static class DVD
    {
        //连接数据库过程数据库的配置管理器要打开
        //数据库  server=服务器 uid=用户名 pwd=密码 database=数据库名
        static string str = "server=;uid=;pwd=;database=";
        //非查询(增删改)
        public static int FaiChuXun(string sql)
        {
            //链接数据库
            SqlConnection df = new SqlConnection(str);
            //打开数据库
            df.Open();
            //获取数据
            SqlCommand gh = new SqlCommand(sql, df);
            //关闭数据库
            df.Close();
            int we = gh.ExecuteNonQuery();
            return we;
        }
        //查询
        public static DataTable ChuXun(string sql)
        {
            //链接数据库获取数据
            SqlDataAdapter qw = new SqlDataAdapter(str, sql);
            //创建表
            DataTable cv = new DataTable();
            //填充数据表
            qw.Fill(cv);
            return cv;
        }
    }
}

登录( 查询)

//1.获取数据
            string name = TextBox1.Text.Trim();
            string pwd = TextBox2.Text.Trim();
            string sql = $"select * from userInfo where name = '{name}' and pwd = '{pwd}'";

            //2.创建新的数据验证类:DBhelper
            DataTable dt = DDSC.DVD.ChaXun(sql);
            //3.检查账户密码是否正确
            if (dt.Rows.Count == 1)
            {
                Literal1.Text = "登陆成功";
            }
            else
            {
                Response.Write("<script>alert('账号或者密码错误')</script>");
            }

GridView后台绑定

前台 点击属性在 点击闪电符 最后点击一下的

RowcancelingEdit逻辑

RowDeleted行删除

RowEditing行逻辑

RowUpdating行距

SelectedIndexChanged事件

后台逻辑与删除
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _10Gridview代码实现删除修改
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Bind();
            }
        }

        //数据绑定方法
        private void Bind()
        {
            string sql = "select * from movieinfo";
            DataTable dt = DAL.DBHelper.GetData(sql);
            //将表绑定在gridview
            GridView1.DataSource = dt;
            //设定主键
            GridView1.DataKeyNames = new string[] { "id" };
            GridView1.DataBind();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //1.找到你要删除的是第几行
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();

            string sql = $"delete from MovieInfo where Id={id}";

            int r = DAL.DBHelper.ExecuteSql(sql);
            if (r > 0)
            {
                Response.Write("<script>alert('删除成功')</script>");
            }

            //重新绑定
            Bind();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //1.找到编辑行
            //string id = GridView1.DataKeys[e.NewEditIndex].Value.ToString();
            GridView1.EditIndex = e.NewEditIndex;

            //2.再次绑定
            Bind();
            

        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //1.找到当前行索引的ID值
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();

            //2.找到修改后的值
            string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
            string dir = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
            string ac = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
            string intro = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
            //3.执行更新的SQL语句
            string sql = $"update MovieInfo set mName='{name}',Director='{dir}',Actor='{ac}'," +
                $"Intro='{intro}' where Id={id}";
            DAL.DBHelper.ExecuteSql(sql);
            //4.不选中任何行:非编辑状态
            GridView1.EditIndex = -1;

            //5.再次绑定
            Bind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;

            //5.再次绑定
            Bind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            int i;
            //执行循环,保证每条数据都可以更新
            for (i = 0; i <= GridView1.Rows.Count; i++)
            {
                //首先判断是否是数据行
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //当鼠标停留时更改背景色
                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='Blue';this.style.cursor='pointer'");
                    //当鼠标移开时还原背景色
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                }
            }

        }

     
    }
}

文件上传

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 文件上传
{
    public partial class fileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //1.判断有没选中图片
            if (!FileUpload1.HasFile)
            {
                Response.Write("<script>alert('未选中任何文件')</script>");
                return;
            }

            //选中文件之后
            //jpg,jpeg,png
            //获取文件名  11.1.1.1.1.1.png   split('.')===> 1  png PNG JPG
            //提取后缀,进行判断,如果符合图片格式,上传到服务器,不符合弹窗提示
            string[] fileName = FileUpload1.FileName.Split('.');
            //获取文件类型,并且转换成小写
            string suffix = fileName[fileName.Length - 1].ToLower();
            //判断文件类型是不是图片
            if(suffix=="jpg"|| suffix == "png" || suffix == "jpeg")
            {
                //上传
                //1.现在的时间
                //string newFileName = DateTime.Now.ToLongDateString().ToString() + DateTime.Now.Millisecond          +"."+suffix;
                //2.随机数更改图片名
                string newFileName = Guid.NewGuid().ToString()+"." + suffix;
                FileUpload1.SaveAs(Server.MapPath(".")+"/img/"+ newFileName);
                   	//		存储为		主路径		   图片存储文件夹名      图片名
                //显示在img控件中
                Image1.Height = 200;
                Image1.Width = 200;
                Image1.ImageUrl = "img/"+ newFileName;

            }
            else
            {
                Response.Write("<script>alert('文件格式错误')</script>");
            }

        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值