温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Button控件与数据库交互示例

发布时间:2024-08-31 14:41:48 来源:亿速云 阅读:82 作者:小樊 栏目:移动开发

在这个示例中,我们将创建一个简单的Windows Forms应用程序,其中包含一个Button控件和一个Label控件

  1. 首先,确保已安装SQL Server并创建一个名为"TestDB"的数据库。然后,在该数据库中创建一个名为"Users"的表,包含以下列:Id(int,主键),Name(nvarchar(50))和Age(int)。

  2. 在Visual Studio中创建一个新的Windows Forms应用程序项目。

  3. 从工具箱中,将一个Button控件和一个Label控件添加到Form上。

  4. 双击Button控件以生成Click事件处理程序。

  5. 在项目中添加对System.Data.SqlClient的引用。

  6. 在Form的代码文件中,添加以下代码:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private SqlConnection _connection;

        public Form1()
        {
            InitializeComponent();

            // 连接字符串,根据实际情况修改
            string connectionString = "Server=localhost;Database=TestDB;Integrated Security=True";
            _connection = new SqlConnection(connectionString);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 打开数据库连接
                _connection.Open();

                // 查询数据库中的用户数量
                string query = "SELECT COUNT(*) FROM Users";
                using (SqlCommand command = new SqlCommand(query, _connection))
                {
                    int userCount = (int)command.ExecuteScalar();

                    // 更新Label控件的文本
                    label1.Text = $"用户数量:{userCount}";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 关闭数据库连接
                if (_connection.State == System.Data.ConnectionState.Open)
                {
                    _connection.Close();
                }
            }
        }
    }
}

现在,当您运行应用程序并单击按钮时,应用程序将连接到数据库,查询用户数量并将结果显示在Label控件中。请注意,您需要根据实际情况修改连接字符串。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI