//web.config 页面
<connectionStrings>
<add name="admin" connectionString="Data Source=(local)\MSSQLSERVER2008;Initial Catalog=USBbuilding;User ID=liuming;Password=111111" providerName="System.Data.SqlClient"/>
</connectionStrings>
// 创建连接数据库
public class conn
{
public static SqlConnection GetSqlconn()
{
SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["admin"].ConnectionString);
return sqlconn;
}
}
//linq to model层,拖入表格进去
//页面添加按钮
<asp:Button ID="Button1" runat="server" Text="提 交" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="编 辑" onclick="Button2_Click" />
//CS页面代码
protected void Button1_Click(object sender, EventArgs e)
{
TableDataContext Tdc = new TableDataContext();
Tdc.addD_News.Title = title.Text;
Tdc.addD_News.Author = author.Text;
Tdc.addD_News.CopyFrom = copyfrom.Text;
Tdc.addD_News.CreateTime =Convert.ToDateTime(createtime.Text);
Tdc.addD_News.Contented = contented.Value;
if (CheckBox1.Checked == true)
{
Tdc.addD_News.State = "1";
}
else
{
Tdc.addD_News.State = "0";
}
Tdc.addD_News.Droped = false;
Tdc.D_NewsTable().InsertOnSubmit(Tdc.addD_News);
Tdc.Dc.SubmitChanges();
JudgJavaScript.Alert("添加成功");
}
protected void Button2_Click(object sender, EventArgs e)
{
TableDataContext Tdc = new TableDataContext();
var uptheid = Tdc.D_NewsTable().Single(i => i.Id == int.Parse(hidid.Value));
uptheid.Title = title.Text;
uptheid.Title = title.Text;
uptheid.Author = author.Text;
uptheid.CopyFrom = copyfrom.Text;
uptheid.CreateTime = Convert.ToDateTime(createtime.Text.ToString());
uptheid.Contented = contented.Value;
if (CheckBox1.Checked == true)
{
uptheid.State = "1";
}
else
{
uptheid.State = "0";
}
Tdc.Dc.SubmitChanges();
JudgJavaScript.Alert("修改成功");
}
//这里,你注意"TableDataContext Tdc = new TableDataContext(); "
public DataContext Dc = new DataContext(conn.GetSqlconn());
//---- D_News 数据表;
public D_News addD_News =new D_News();
public Table<D_News> D_NewsTable()
{
Table<D_News> table=Dc.GetTable<D_News>();
return table;
}
// 上面就是数据库表,持久层,以后对Linq的DataContext 可以重复使用了。