前台HTML代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Insert.aspx.cs" Inherits="Insert" %>
<!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>
<h1>添加数据</h1>
</div>
<asp:Label ID="Label1" runat="server" Text="代号:"></asp:Label>
<asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="姓名:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="性别:"></asp:Label>
<asp:RadioButton ID="rdMan" runat="server" Checked="True" GroupName="sex" Text="男" />
<asp:RadioButton ID="rdWomen" runat="server" GroupName="sex" Text="女" />
<br />
<br />
<asp:Label ID="Label4" runat="server" Text="民族:"></asp:Label>
<asp:DropDownList ID="drNation" runat="server">
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label5" runat="server" Text="生日:"></asp:Label>
<asp:TextBox ID="txtBirthday" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="确定" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="返回" />
</form>
</body>
</html>
后台C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Insert : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["uid"] != null)
{
if (!IsPostBack)
{
//给下拉列表帮上数据
testDataContext context = new testDataContext();
drNation.DataSource = context.Nation;
drNation.DataTextField = "Name";
drNation.DataValueField = "Code";
drNation.DataBind();
}
}
else
{
Response.Redirect("DengLu.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
testDataContext context = new testDataContext();
//取值
string code = txtCode.Text;
string name = txtName.Text;
bool sex = rdMan.Checked;
string nation = drNation.SelectedValue;
DateTime birthday = Convert.ToDateTime(txtBirthday.Text);
// 造对象 给对象附上值
Info data = new Info();
data.Code = code;
data.Name = name;
data.Sex = sex;
data.Nation = nation;
data.Birthday = birthday;
//添加到数据库
context.Info.InsertOnSubmit(data);
context.SubmitChanges();
ClearAll();
}
public void ClearAll()
{
txtCode.Text = "";
txtName.Text = "";
txtBirthday.Text = "";
rdMan.Checked = true;
drNation.SelectedIndex = 0;
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Main.aspx");
}
}
网页显示:

原文:http://www.cnblogs.com/zhuxu/p/5064786.html