C#利用WinForm調用WebServices實現增刪改查


實習導師要求做一個項目,用Winform調用WebServices實現增刪改查的功能。寫下這篇博客,當做是這個項目的總結。如果您有什么建議,可以給我留言。歡迎指正。

1、首先,我接到這個項目的時候,根本不清楚什么是WebServices,所以第一步,我要搞清楚什么是WebServices。現在有個模糊的概念,比如,中國天氣網想把每天的天氣狀況給用戶查詢,它當然不可能讓用戶直接訪問它的數據庫。所以,中國天氣網就把查詢天氣之類的方法寫進WebServices中,讓用戶去WebServices調用這些接口,從而達到查詢天氣的目的。

2、緊接着,由於我們是發布一個WebServices來讓其他人調用。所以我們要在本機上配置IIS服務器。具體步驟如下:

1-->打開計算機,找到卸載或更改程序

2-->找到啟用或關閉Windows功能

3-->把下面這三個東西全部點上(我也不知道怎么點,我把所有的都點上了)

4-->點擊確定,此時我們的IIS應該就已經配置完畢了。

5-->現在我們去服務中找到IIS服務。看到此選項,應該可以說明,我們的IIS配置完畢了。

 

3、IIS配置完畢之后,此時,我們便可以在VS中編寫Web程序。

1-->新建一個空的Web應用程序

2-->這個時候我們就會看到有一個ceshiWebServices的項目,右擊添加新項,選擇Web服務,名稱可以隨意。

3-->此時我們可以看到一個默認的Hello World方法

4-->下面我們來將此Web服務發布,步驟如下:(1)首先右擊項目,點擊發布。(2)接着按照圖片的步驟來

 

 

 

 

 

 

 

 

此時,我們的Web服務應該已經發布完畢。

5-->下面,我們去IIS服務器中,瀏覽看一下。

 

6-->此時要注意的是,我們需要啟用目錄瀏覽

 

 

 7-->找到右面板,點擊瀏覽。如果沒有問題,將會出現以下界面。(有時候會報出一些莫名奇妙的錯誤,如403,404,409之類的,遇到此類問題,百度一下)

 

8-->目前為止,我們發布WebServices就成功了。

 

4、下面我們就用Winform程序來調用此WebServices,因為我的目的是利用調用此WebServices實現增刪改查功能,所以接下來就直接上代碼。

1-->WebServices增刪改查功能代碼實現(僅  1 public class Infos : System.Web.Services.WebService

 2  {  3 
 4  [WebMethod]  5         public string HelloWorld()  6  {  7             return "Hello World";  8  }  9 
 10  [WebMethod]  11         public DataSet select(int userid,string username)  12  {  13             try
 14  {  15                 DataSet ds = new DataSet();  16                 string constr = "Data source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456";  17                 using (SqlConnection con = new SqlConnection(constr))  18  {  19                     if (con.State == ConnectionState.Closed)  20  {  21  con.Open();  22  }  23                     string sql = "select * from TB_UserInfo where userid='" + userid + "' or username='" + username + "'";  24                     SqlDataAdapter da = new SqlDataAdapter(sql, con);  25  da.Fill(ds);  26  con.Close();  27  }  28                 return ds;  29  }  30             catch (Exception ex)  31  {  32                 return new DataSet();  33  }  34            
 35  }  36 
 47  [WebMethod]  48 
 49         public bool add(string UserID, string UserName, string UserSex, string UserAge, string UserPassword, string UserType)  50  {  51           string constr = "Data source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456";  52           using (SqlConnection con = new SqlConnection(constr))  53  {  54                string sql = "insert into TB_UserInfo values ('"+UserID+"','"+UserName+"','"+UserSex+"','"+UserAge+"','"+UserPassword+"','"+UserType+"')";  55                 using (SqlCommand cmd = new SqlCommand(sql, con))  56  {  57                     try
 58  {  59  con.Open();  60  cmd.ExecuteNonQuery();  61  con.Close();  62                         return true;  63  }  64                     catch (Exception ex)  65  {  66                         return false;  67  }  68  }  69  }  70  }  71 
 72  [WebMethod]  73 
 74         public bool delete(string UserID,ref string errormessage)  75  {  76             string constr = "Data Source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456";  77             using (SqlConnection con = new SqlConnection(constr))  78  {  79                 string sql ="delete from TB_UserInfos where UserID='"+UserID+"'";  80                 using (SqlCommand cmd = new SqlCommand(sql, con))  81  {  82                     try
 83  {  84  con.Open();  85  cmd.ExecuteNonQuery();  86  con.Close();  87                         return true;  88  }  89                     catch (Exception ex)  90  {  91                         errormessage=ex.Message.ToString();  92                         return false;  93  }  94                    
 95  }  96  }  97  }  98 
 99  [WebMethod] 100         public bool update(string UserID, string UserName, string UserSex, string UserAge, string UserPassword, string UserType, ref string errormessage) 101  { 102             string constr = "Data Source=.;Initial Catalog=DB_UserSystem;User ID=sa;Password=123456"; 103             using (SqlConnection con = new SqlConnection(constr)) 104  { 105                 string sql = "update TB_UserInfo set UserName='"+UserName+"',UserSex='"+UserSex+"',UserAge='"+UserAge+"',UserPassword='"+UserPassword+"',UserType='"+UserType+"' where UserID='"+UserID+"'"; 106                 using (SqlCommand cmd = new SqlCommand(sql, con)) 107  { 108                     try
109  { 110  con.Open(); 111  cmd.ExecuteNonQuery(); 112  con.Close(); 113                         return true; 114  } 115                     catch (Exception ex) 116  { 117                         errormessage = ex.Message.ToString(); 118                         return false; 119  } 120  } 121                 
122  } 123  } 124  } 125     

2-->因為我的WinForm已經做好了,所以接下來就在此基礎上進行操作。

界面如下:

3-->我們首先要引用Web服務的地址,我們找到剛才發布Web服務的地址,http://localhost:1666/Infos.asmx,由於我是直接在我以前做的基礎上做的,上一個Web服務是新建的,里面方法什么的也沒有寫,所以我就貼了我做好了Web地址。

這個時候找到WinForm所在的項目,右擊-->添加-->服務引用

地址輸入我們之前發布WebServices的地址,由於我已經添加引用,這里我就不再折騰一遍了。

4-->由於我們要調用WebServices,所以我們先要將它實例化。

代碼如下:(僅供參考)

由於我也是今天剛在老師的指導下完成,對於一些代碼也是一知半解。所以這里就直接貼上來,方便明天繼續思考和練習。

namespace WindowsFormsApplication14
{
    public partial class Form1 : Form
    {

        private ServiceReference.InfosSoapClient ws;  //這樣就省得在每一個方法中都實例化了
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO:  這行代碼將數據加載到表“dB_UserSystemDataSet.TB_UserInfo”中。您可以根據需要移動或刪除它。
            //this.tB_UserInfoTableAdapter.Fill(this.dB_UserSystemDataSet.TB_UserInfo);
            //LoadData();
            ws = new ServiceReference.InfosSoapClient();  //同上
        }

      
        private void button1_Click(object sender, EventArgs e)
        {

            string UserID = txtUserID.Text.Trim();
            string UserName = txtUserName.Text.Trim();
            string UserSex = this.comboBox2.Text;
            string UserAge = txtUserAge.Text;
            string UserPassword = txtUserPassword.Text;
            string UserType = this.comboBox3.Text;

            string errorinfo = "";

            if (ws.add(txtUserID.Text, txtUserName.Text, this.comboBox2.Text, txtUserAge.Text, txtUserPassword.Text, this.comboBox3.Text, ref errorinfo))
            {
                MessageBox.Show("注冊成功" + errorinfo);
            }
            else
            {
                MessageBox.Show("注冊失敗" + errorinfo);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int UserAge=0;

            try
            {
                int.Parse(txtUserAge.Text);
                UserAge = Convert.ToInt32(txtUserAge.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("輸入不正確", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }

            string errorinfo = "";
            if (ws.update(txtUserID.Text,txtUserName.Text,this.comboBox2.Text,txtUserAge.Text,txtUserPassword.Text,this.comboBox3.Text,ref errorinfo))
            {
                MessageBox.Show("更新成功" );
            }
            else
            {
                MessageBox.Show("更新失敗" );
            }           
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("確定要刪除嗎?", "操作提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string errorinfo = "";
                if (ws.delete(txtUserID.Text, ref errorinfo))
                {
                    MessageBox.Show("刪除成功" + errorinfo);
                }
                else
                {
                    MessageBox.Show("刪除失敗" + errorinfo);
                }
            }


        }

        private void button4_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            if (comboBox1.SelectedIndex >= 0)
            {
                if (comboBox1.SelectedIndex == 0)
                {
                    ds = ws.select(Convert.ToInt32(textBox1.Text), "");
                }
                else if (comboBox1.SelectedIndex == 1)
                {
                    ds = ws.select(0, textBox1.Text);
                }
                dgv.DataSource = ds.Tables[0];
            }

            //this.showResult();
        }

    }

}

這里需要注意一點:

   就是當我們在WebServices里面更新語句的時候,我們一定要回到我們的WinForm項目中,更新服務引用。

 

5-->至此我們調用WebServices就告一段落。

 

第一次寫博客,加上做出來嚴格意義上人生第一個項目,導致現在興奮不減,思路混亂,文章寫的一團亂麻,請大家見諒,給我提出寶貴意見。

 

加上一點閑扯淡:

  感覺人有時候真的很賤,以前大學的時候,天天躺在宿舍,一副無所事事的樣子,很想找一些事情做,讓自己進步。現在,一要真的開始成長了,莫名其妙開始懷念以前躺在宿舍那段無聊的時光。我想,這應該是畏懼,因為實習所接觸的東西都是以前沒有接觸過的,畏懼失敗,害怕自己做的不好。像拿到這個項目的時候,我的第一個想法,不是如何去設計,如何自己想着怎么去寫代碼。而想的是,去找視頻教程,去找源代碼,一步到位。后來發現這是不可能的,就算找到源代碼,下一次還是不會。所以,我現在應該應該轉變一個思路,做中學,先做,遇到不會的,自己想辦法解決,如果無法解決,向老師,百度請教。這樣做出來一個項目,自己也很享受解決問題的過程,也會很有成就感。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM