• 浅谈ListBox控件,将对象封装在listBox中,在ListBox中显示对象中某个属性,在ListBox中移除和移动信息


        

         大家好,俗称万事开头难,不经历风雨,怎能见彩虹。在此小编给大家带来一个自己练习的小实例,希望与大家一起分享与交流。下面进入应用场景,从SQL2008数据库取出数据,给ListBox赋值在界面并显示出来,通过窗体应用程序上Button控件,执行移动、移除等功能。

    开发环境

         开发工具:Microsoft Visual Studio 旗舰版、SQL Server 2008.

         开发环境:.NET Framework 4 Client Profile.

    实现步骤

    1、搭建MVC框架、建立PERSON_T表格;

        首先,了解什么是MVC框架,MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用于组织代码用一种业务逻辑和数据显示分离的方法,这个方法的假设前提是如果业务逻辑被聚集到一个部件里面,而且界面和用户围绕数据的交互能被改进和个性化定制而不需要重新编写业务逻辑MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

    我在VS项目中建立一个目录如下图:

    项目结构

       然后,在SQL2008中FMSDB数据库中建立PERSON_T表;具体代码见下方:

    USE [FMSDB]
    GO
    
    /****** Object:  Table [dbo].[PERSON_T]    Script Date: 07/30/2013 15:47:33 ******/
    SET ANSI_NULLS ON
    GO
    
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE TABLE [dbo].[PERSON_T](
        [NAME] [nvarchar](50) NULL,
        [AGE] [int] NULL
    ) ON [PRIMARY]
    
    GO
     

    2、与SQL 2008建立连接、查询和删除信息;

    首先,给数据库创建一个实例FMSDB,再给FMSDB资料库创建一个PERSON_T表,新添用户“root”,密码“12345”;能成功连接上数据库服务器,

    数据库连接具体见下图:

    数据库连接

    App.config 与数据库连接具体代码见下:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <appSettings>
        <add key="myDatabase.Conn" value="Data Source=localhost,1433;Network Library=DBMSSOCN;Initial Catalog=FMSDB;User ID=root;Password=12345;" />
      </appSettings>
    </configuration>
    SelectGW.cs中具体代码见下:其中需要添加引用System.Configuration、System.Data.SqlClient.
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace ListBoxUnit1.DataGateway
    {
        public class SelectGW
        {
            private string connectString = "";
    
            public SelectGW()
            {
                connectString = ConfigurationManager.AppSettings["myDatabase.Conn"];
            }
    
            public SqlConnection GetSqlConnection()
            {
                SqlConnection conn = new SqlConnection(connectString);
                conn.Open();
                return conn;
            }
    
            public DataSet GetPersonData()
            {
                DataSet ds = new DataSet();
                string sqlText = @"SELECT * FROM PERSON_T;";
                try
                {
                    SqlConnection conn = GetSqlConnection();
                    SqlCommand sqlCommand = conn.CreateCommand();
                    sqlCommand.CommandText = sqlText;
                    sqlCommand.CommandType = CommandType.Text;
                    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
    
                    sqlDataAdapter.Fill(ds);
                }
                catch (Exception ex)
                {
                   
                }
                return ds;
            }
    
            public int DeleteUserInfoData(string NAME)
            {
                string sqlText = @"delete  FROM PERSON_T where NAME='{0}';";
                sqlText = string.Format(sqlText, NAME);
                try
                {
                    SqlConnection conn = GetSqlConnection();
                    SqlCommand sqlCommand = conn.CreateCommand();
                    sqlCommand.CommandText = sqlText;
                    sqlCommand.CommandType = CommandType.Text;
                    int i=sqlCommand.ExecuteNonQuery();
                    return i;
                }
                catch (Exception ex)
                {
                    return 0;
                }
            } 
        }
    }

    3、建立一个Person对象,重载用户姓名;

    Person.cs中具体代码见下:

    namespace ListBoxUnit1
    {
        public class Person
        {
            private int _age;
    
            public int Age
            {
                get { return _age; }
                set { _age = value;}
            }
            private string _name;
    
            public string Name
            {
                get { return _name; }
                set { _name = value;}
            }
            public override string ToString()
            {
                return this._name;
            }
        }
    }

    4、在控制层中主要代码如下Controller.cs:

    using System.Collections.Generic;
    using System.Data;
    using ListBoxUnit1.DataGateway;
    
    namespace ListBoxUnit1.Core
    {
       public class Controller
       {
           public SelectGW GW;
           public Controller()
           {
               GW =new SelectGW();
           }
    
           public List<Person> GetUserInfo()
           {
               List<Person> persons = new List<Person>();
               DataSet ds = GW.GetPersonData();
               if (ds.Tables[0].Rows.Count > 0)
                   for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                   {
                       Person p = new Person();
                       p.Name = ds.Tables[0].Rows[i][0].ToString();
                       p.Age = int.Parse(ds.Tables[0].Rows[i][1].ToString());
                       persons.Add(p);
                   }
               return persons;
           }
    
           public bool DeleteUser(string name)
           {
               bool result=false;
               int i= GW.DeleteUserInfoData(name);
               if (i > 0)
               {
                   result = true;
               }
               return result;
           }
       }
    }

    5、在视图层主要代码MainFrom.cs具体如下:

    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;
    using ListBoxUnit1.Core;
    
    
    namespace ListBoxUnit1
    {
        public partial class MainForm : Form
        {
            private Controller Control;
    
            public MainForm()
            {
                InitializeComponent();
                Control = new Controller();
            }
    
            private void MainForm_Load(object sender, EventArgs e)
            {
    
                List<Person> persons = new List<Person>();
    
                persons = Control.GetUserInfo();
                for (int i = 0; i < persons.Count; i++)
                {
                    listBoxFor.Items.Add(persons[i]);
                    listBoxFor.SelectedIndex = 0;
                }
            }
    
            private void btnAdd_Click(object sender, EventArgs e)
            {
                if (listBoxFor.SelectedItems.Count == 0)
                {
                    MessageBox.Show("没选中添加用户信息");
                }
                else
                {
                    listBoxForeach.Items.Add(listBoxFor.SelectedItem);
                    listBoxFor.Items.Remove(listBoxFor.SelectedItem);
                }
    
            }
    
            private void btnRemove_Click(object sender, EventArgs e)
            {
             
                if (listBoxFor.SelectedItem != null)
                {
                   
                    DialogResult comfirm = MessageBox.Show("确定删除选中信息...", "确定删除", MessageBoxButtons.YesNo,
                                                           MessageBoxIcon.Exclamation);
                    if (comfirm == DialogResult.Yes)
                    {
                        string Name = listBoxFor.SelectedItem.ToString();
                        bool result = Control.DeleteUser(Name);
                        if (result)
                        {
                            listBoxFor.Items.Remove(listBoxFor.SelectedItem);
                        }
                    }
                }
    
            }
    
            private void btnLeft_Click(object sender, EventArgs e)
            {
                if (listBoxForeach.SelectedItems.Count == 0)
                {
                    MessageBox.Show("没选中添加用户信息");
                }
                else
                {
                    listBoxFor.Items.Add(listBoxForeach.SelectedItem);
                    listBoxForeach.Items.Remove(listBoxForeach.SelectedItem);
                }
            }
        }
    }

    效果图

    窗体载入画面

    主画面图片

    可以删除左边选中一栏一个信息,单击移除

    删除选中用户

    删除成功后界面图

    删除成功后

    技术点

    熟悉ListBox的一些基本用法,实现数据移除和移动的功能;

    了解MVC框架后,将MVC框架思想应用到实际例子中;

    建立Person对象,通过重载用户名后,显示在界面的只是Person对象上的一个属性;

    利用SQL进行数据的查询与删除,同时更新视图层的信息;

    熟练运用If…else语句,才能将控制能做好。

    问题疑惑

    怎样能将控制做完善,才能让系统经得起考验,不会出现奔溃或bug。

    怎么让面向对象的编程能够灵活运用起来。

    感想

    通过几天的劳作,将代码分享一下,中间肯定存在不足,希望大家提供好的建议,通过这次锻炼,熟悉了面向对象编程、以及MVC系统框架的搭建有了一些了解、掌握建立于SQL数据库的链接的方法等。

    源码下载

  • 相关阅读:
    第七章 Net 5.0 快速开发框架 YC.Boilerplate -- 数据层ORM 设计
    第六章 Net 5.0 快速开发框架 YC.Boilerplate -- 代码生成和数据库表生成
    第五章 Net 5.0 快速开发框架 YC.Boilerplate -- 缓存模块
    第四章 Net 5.0 快速开发框架 YC.Boilerplate-- 动态WebApi
    第三章 Net 5.0 快速开发框架 YC.Boilerplate-- 多租户介绍
    第二章 Net 5.0 快速开发框架 YC.Boilerplate-- 快速入门
    第一章 Net 5.0 快速开发框架 YC.Boilerplate--框架介绍
    【雕爷学编程】Arduino动手做(90)---4X4矩阵薄膜键盘模块
    【雕爷学编程】Arduino动手做(89)---8位双向电平转换模块
    多端自动化运行:pc+android+ios+小程序 均可
  • 原文地址:https://www.cnblogs.com/chenghui/p/3226852.html
Copyright © 2020-2023  润新知