SilverLight中使用WebService对数据库做CRUD

SilverLight中使用WebService对数据库做CRUD,第1张

概述SilverLight中使用WebService对数据库做CRUD   1.       新建一个asmx文件       public class MainService : System.Web.Services.WebService     {         #region User CRUD         [WebMethod]         public bool CreateUs

Silverlight中使用WebService对数据库做CRUD

 

1.       新建一个asmx文件

 

    public class MainService : System.Web.Services.WebService

    {

        #region User CRUD

        [WebMethod]

        public bool createuser(string username)

        {

            try

            {

                sqlConnection _sqlConnection = new sqlConnection();

                _sqlConnection.ConnectionString = ConfigurationManager.

                    ConnectionStrings["sqlConnectionString"].ToString();

                _sqlConnection.open();

                sqlCommand command = new sqlCommand();

                command.Connection = _sqlConnection;

                command.CommandType = CommandType.Text;

                command.CommandText = "INSERT INTO [User] ([Username]) VALUES ('" +

                    username.ToString().Replace("'","''") + "')";

                command.ExecuteNonquery();

                _sqlConnection.Close();

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

 

 

        [WebMethod]

        public string RetrIEveUser(int userID)

        {

            try

            {

                sqlConnection _sqlConnection = new sqlConnection();

                _sqlConnection.ConnectionString = ConfigurationManager.

                    ConnectionStrings["sqlConnectionString"].ToString();

                _sqlConnection.open();

                sqlDataAdapter da = new sqlDataAdapter();

                da.SelectCommand = new sqlCommand("SELECT * FROM [User] WHERE [UserID] = " +

                    userID.ToString().Replace("'","''"),_sqlConnection);

                DataSet ds = new DataSet();

                da.Fill(ds);

                StringBuilder sb = new StringBuilder();

                sb.Append("<?xml version=/"1.0/" enCoding=/"utf-8/" ?>");

                sb.Append("<Users>");

                foreach (DaTarow dr in ds.tables[0].Rows)

                {

                    sb.Append("<User>");

                    sb.Append("<ID>");

                    sb.Append(dr[0].ToString());

                    sb.Append("</ID>");

                    sb.Append("<name>");

                    sb.Append(dr[1].ToString());

                    sb.Append("</name>");

                    sb.Append("</User>");

                }

                sb.Append("</Users>");

 

                _sqlConnection.Close();

                return sb.ToString();

            }

            catch (Exception ex)

            {

                return string.Empty;

            }

        }

 

        [WebMethod]

        public string RetrIEveUsers()

        {

            try

            {

                sqlConnection _sqlConnection = new sqlConnection();

                _sqlConnection.ConnectionString = ConfigurationManager.

                    ConnectionStrings["sqlConnectionString"].ToString();

                _sqlConnection.open();

                sqlDataAdapter da = new sqlDataAdapter();

                da.SelectCommand = new sqlCommand("SELECT * FROM [User]",_sqlConnection);

                DataSet ds = new DataSet();

                da.Fill(ds);

 

                StringBuilder sb = new StringBuilder();

                sb.Append("<?xml version=/"1.0/" enCoding=/"utf-8/" ?>");

                sb.Append("<Users>");

                foreach (DaTarow dr in ds.tables[0].Rows)

                {

                    sb.Append("<User>");

                    sb.Append("<UserID>");

                    sb.Append(dr[0].ToString());

                    sb.Append("</UserID>");

                    sb.Append("<Username>");

                    sb.Append(dr[1].ToString());

                    sb.Append("</Username>");

                    sb.Append("</User>");

                }

                sb.Append("</Users>");

 

                _sqlConnection.Close();

                return sb.ToString();

            }

            catch (Exception ex)

            {

                return string.Empty;

            }

        }

 

        [WebMethod]

        public bool UpdateUser(int userID,string username)

        {

            try

            {

                sqlConnection _sqlConnection = new sqlConnection();

                _sqlConnection.ConnectionString = ConfigurationManager.

                    ConnectionStrings["sqlConnectionString"].ToString();

                _sqlConnection.open();

                sqlCommand command = new sqlCommand();

                command.Connection = _sqlConnection;

                command.CommandType = CommandType.Text;

                command.CommandText = "UPDATE [User] " +

                    "SET [Username] = '" + username.ToString().Replace("'","''") + "'" +

                    "WHERE [UserID] = " + userID.ToString();

                command.ExecuteNonquery();

                _sqlConnection.Close();

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

 

        [WebMethod]

        public bool DeleteUser(int userID)

        {

            try

            {

                sqlConnection _sqlConnection = new sqlConnection();

                _sqlConnection.ConnectionString = ConfigurationManager.

                    ConnectionStrings["sqlConnectionString"].ToString();

                _sqlConnection.open();

                sqlCommand command = new sqlCommand();

                command.Connection = _sqlConnection;

                command.CommandType = CommandType.Text;

                command.CommandText = "DELETE [User] WHERE [UserID] = " + userID.ToString();

                command.ExecuteNonquery();

                _sqlConnection.Close();

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

        #endregion

 

}

 

2.      设置xaml页面文件

  <data:DataGrID x:name="dgWork" Background="Aquamarine" Height="200"

               WIDth="700" margin="0,5,10"

              autoGenerateColumns="False"  >

                    <data:DataGrID.Columns>

                        <data:DataGrIDTextColumn header="用户ID" IsReadonly="True"  WIDth="80"  Binding="{Binding UserID}" />

                        <data:DataGrIDTextColumn header="用户名称" IsReadonly="True"  WIDth="200"   Binding="{Binding Username}" />

                    </data:DataGrID.Columns>

                    

                </data:DataGrID>

 

3.      Silverlight项目中新建实体类

    public class User

    {

        public int UserID { get; set; }

        public string Username { get; set; }

}

 

4.      调用WebService,并显示数据

 

  public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            Loaded += new RoutedEventHandler(MainPage_Loaded);

 

        }

        private voID MainPage_Loaded(object sender,RoutedEventArgs e)

        {

            ListingControldisplay();

        }

 

        /// <summary>

        /// 显示数据

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        voID ListingControldisplay()

        {

            MainServiceSoapClIEnt userMgrSoapClIEnt = new MainServiceSoapClIEnt();

            userMgrSoapClIEnt.RetrIEveUsersAsync();

            userMgrSoapClIEnt.RetrIEveUsersCompleted += new EventHandler<RetrIEveUsersCompletedEventArgs>(userMgrSoapClIEnt_RetrIEveUsersCompleted);

        }

        /// <summary>

        /// 取数完成后,显示数据

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        voID userMgrSoapClIEnt_RetrIEveUsersCompleted(object sender,MainService.RetrIEveUsersCompletedEventArgs e)

        {

            if (e.Error == null)

            {

                displayData(e.Result);

            }

        }

 

        /// <summary>

        /// 显示数据到界面上

        /// </summary>

        /// <param name="xmlContent"></param>

        private voID displayData(string xmlContent)

        {

            if (xmlContent != string.Empty)

            {

                Xdocument xmlUsers = Xdocument.Parse(xmlContent);

                var users = from user in xmlUsers.Descendants("User")

                            select new

                            {

                                UserID = Convert.ToInt32

                                          (user.Element("UserID").Value),

                                Username = (string)

                                          user.Element("Username").Value

                            };

                List<User> usersList = new List<User>();

                foreach (var u in users)

                {

                    User use = new User { UserID = u.UserID,Username = u.Username };

                    usersList.Add(use);

                }

                dgWork.ItemsSource = usersList;

            }

            else

            {

                dgWork.ItemsSource = null;

            }

 

        }

 

}

总结

以上是内存溢出为你收集整理的SilverLight中使用WebService对数据库做CRUD全部内容,希望文章能够帮你解决SilverLight中使用WebService对数据库做CRUD所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1046144.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存