⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usercontrolexample.ascx.cs

📁 asp.net专家200问(含源代码解决法案
💻 CS
字号:
namespace Example
{
	using System;
	using System.Data;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Data.SqlClient;

	public class UserControlExample : System.Web.UI.UserControl
	{
		protected System.Web.UI.WebControls.TextBox usernameTextBox;
		protected System.Web.UI.WebControls.TextBox passwordTextBox;
		protected System.Web.UI.WebControls.TextBox nickTextBox;
		protected System.Web.UI.WebControls.TextBox emailTextBox;
		protected System.Web.UI.WebControls.Button LoginButton;
		protected System.Web.UI.WebControls.Panel InputPanel;
		protected System.Web.UI.WebControls.Panel AddSuccessPanel;

		private void Page_Load(object sender, System.EventArgs e)
		{

		}

		public void LoginButton_Click(object sender, EventArgs e)
		{
			SaveNewUser();
		}

		private void SaveNewUser()
		{
			// 连接字符串和SQL语句
            string Sql = "INSERT INTO Users (username,password,nick,email) VALUES "
				+ " (@username,@password,@nick,@email)";
			string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer_tempdb"];

			// 创建Connection和Command对象
			SqlConnection myConn = new SqlConnection(ConnStr);
			SqlCommand myCommand = myConn.CreateCommand();

			// 初始化Command对象
			myCommand.CommandText = Sql;
			myCommand.CommandType = CommandType.Text;

			myCommand.Parameters.Add("@username", SqlDbType.NVarChar, 10);
			myCommand.Parameters["@username"].Value = usernameTextBox.Text;

			myCommand.Parameters.Add("@password", SqlDbType.NVarChar, 10);
			myCommand.Parameters["@password"].Value = passwordTextBox.Text;

			myCommand.Parameters.Add("@nick", SqlDbType.NVarChar, 50);
			myCommand.Parameters["@nick"].Value = nickTextBox.Text;

			myCommand.Parameters.Add("@email", SqlDbType.NVarChar, 50);
			myCommand.Parameters["@email"].Value = emailTextBox.Text;

			try
			{
				myCommand.Connection.Open();
				if(1 == myCommand.ExecuteNonQuery())
				{
					// 新增成功,隐藏输入用户信息的面板,显示“输入成功”的面板
                    InputPanel.Visible = false;
					AddSuccessPanel.Visible = true;
				}
			}
			catch(Exception ex)
			{
				Response.Write("<b>运行本节示例请参见书中介绍,先在tempdb数据库中创建Users表,否则运行会产生错误。</b><br>");
				Response.Write(ex.ToString());
			}
			finally
			{
				myCommand.Connection.Close();
			}
			
		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		设计器支持所需的方法 - 不要使用代码编辑器
		///		修改此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.LoginButton.Click += new System.EventHandler(this.LoginButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -