ASP.NET實現資料的添加(第10節)_實用技巧

來源:互聯網
上載者:User

這節以新聞網站為例實現新聞的添加,並把附件和圖片上傳至伺服器。
學習內容

步驟一 添加新項,建立Web表單並將其命名為“newsadd.aspx”
步驟二 布局頁面,建立6行2列的表格

步驟三  資料來源控制項定義資料的方法,在newschuli.cs頁面中編寫代碼如下:

public static void addnews(newsclass news1)    {      using (SqlConnection cn = dbconn.GetConnection())      {        cn.Open();        SqlCommand cm = new SqlCommand();        cm.Connection = cn;        string sql = "insert news(title,contents,img,annex,time) values(@aa,@bb,@cc,@dd,@ee)";        cm.CommandText = sql;        cm.Parameters.AddWithValue("@aa", news1.Title);        cm.Parameters.AddWithValue("@bb", news1.Contents);        cm.Parameters.AddWithValue("@cc", news1.Img);        cm.Parameters.AddWithValue("@dd", news1.Annex);        cm.Parameters.AddWithValue("@ee", news1.Time);        cm.ExecuteNonQuery();      }    }

步驟四 開啟newsadd.aspx設計頁面,雙擊Button1按鈕,編寫代碼:

protected void Button1_Click(object sender, EventArgs e)  {    newsclass news1 = null;    news1 = new newsclass();    news1.Title = TextBox1.Text.ToString().Trim();    news1.Contents= TextBox2.Text.ToString().Trim();    news1.Img = FileUpload1.FileName.ToString();    news1.Annex= FileUpload2.FileName.ToString();    news1.Time = DateTime.Now.ToString();    newschuli.addnews(news1);        Response.Redirect("NewsCategoriesManager.aspx"); }

步驟五 將上傳的圖片或附件存放到網站中,在Button按鈕下,編寫代碼:

if (FileUpload1.HasFile) {      FileUpload1.SaveAs(Server.MapPath("../upfile" + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName));  } if (FileUpload2.HasFile) {  FileUpload2.SaveAs(Server.MapPath("../upfile" + "\\" +DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload2.FileName)); }

步驟六 運行

運行效果圖:

總結
通過本節的學習,實現了資料的添加,完善了對news的基本操作:尋找,更新,以及今天所學習的新增工作。在此基礎上還擴充了一個知識點—如何將上傳的圖片或附件存放到網站中,希望今天的學習,大家和小編都有所收穫。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.