欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET實現(xiàn)數(shù)據(jù)的添加(第10節(jié))

 更新時間:2022年04月27日 14:49:59   投稿:lijiao  
這篇文章主要介紹了ASP.NET如何實現(xiàn)數(shù)據(jù)的添加,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

這節(jié)以新聞網站為例實現(xiàn)新聞的添加,并把附件和圖片上傳至服務器。

學習內容

步驟一 添加新項,創(chuàng)建Web窗體并將其命名為“newsadd.aspx”
步驟二 布局頁面,創(chuàng)建6行2列的表格

步驟三  數(shù)據(jù)源控件定義數(shù)據(jù)的方法,在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));
 }

步驟六 運行

運行效果圖:

總結

通過本節(jié)的學習,實現(xiàn)了數(shù)據(jù)的添加,完善了對news的基本操作:查找,更新,以及今天所學習的添加任務。在此基礎上還擴充了一個知識點—如何將上傳的圖片或附件存放到網站中,希望今天的學習,大家和小編都有所收獲。

相關文章

最新評論