首页 > 解决方案 > SQL 表没有更新,但我的 datagridview1 在运行时被来自文本框的信息填充

问题描述

我正在尝试使用 C# 和本地 SQL Server 开发库存 Windows Forms 应用程序。不知何故,我的 dataGridView1 正在从本地 SQL Server 表中获取信息,我什至设法使用来自文本框的信息填充 dataGridView1,但是每当我想在存在应用程序后检查 SQL Server 表时,当我去服务器资源管理器 - > Invetory.mdf - > 右键单击​​“显示数据表”,没有存储任何信息,当我单击刷新按钮时,运行时和多次重新初始化后存储的所有内容......都消失了。

我什至重新启动了我的计算机,重新启动时信息保存在 dataGridView1 中,但 SQL Server 表仍然是空的。

public partial class frmMain : Form
{
        SqlConnection connectionsql;
        string  connectionString;

        public frmMain()
        {
            InitializeComponent();
            connectionString = ConfigurationManager.ConnectionStrings["Equipment_Inventory.Properties.Settings.InventoryConnectionString"].ConnectionString;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            populategrid();
        }

        private void populategrid()
        {
            using (connectionsql = new SqlConnection(connectionString))
            using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Inventory", connectionsql))
            {
                DataTable InventoryTable = new DataTable();
                adapter.Fill(InventoryTable);
                dataGridView1.DataSource = InventoryTable;
            }
        }

        private void insert_button(object sender, EventArgs e)
        {
            string query = "insert into Inventory (InternalNumber, Grupa, Type, Manufacturer, Equipment) values (@InternalNumber, @Grupa, @Type, @Manufacturer, @Equipment)";

            using (connectionsql = new SqlConnection(connectionString))
            using (SqlCommand command = new SqlCommand(query, connectionsql))
            {
                connectionsql.Open();
                command.CommandType = CommandType.Text;
                command.Parameters.Add("@InternalNumber", textBox1.Text);
                command.Parameters.Add("@Grupa", textBox2.Text);
                command.Parameters.Add("@Type", textBox3.Text);
                command.Parameters.Add("@Manufacturer", textBox4.Text);
                command.Parameters.Add("@Equipment", textBox5.Text);

                command.ExecuteNonQuery();

                populategrid();
            }
        }
    }
}

我的 datagridview1 在运行时的屏幕截图:

在此处输入图像描述

我的本地 SQL Server 表的屏幕截图:

在此处输入图像描述

我很遗憾在其他 Youtube 视频中,使用这样的代码,SQL 表正在更新。它不是本地 SQL,但仍然......

我将衷心感谢您的帮助。

标签: c#sqldatabase

解决方案


您肯定正在连接到其他一些测试表或您在本地系统上创建的任何其他相同的数据库模式。要验证您是否以该表为目标,您需要手动插入一些行并在您的表单中检查这些行是否加载到 datagridview1 中。之后,您将针对该问题。您的代码中没有任何问题。


推荐阅读