簡體   English   中英

如何刷新我的 DataGridView? 我正在嘗試刷新 datagridview 中的列表,但我不能

[英]How to refresh my DataGridView? I am trying to refresh the list in datagridview but i can't

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PetsHotelSystem.User_Control
{
    public partial class UC_UpdateRoom : UserControl
    {
        function fn = new function();
        string query;

        public UC_UpdateRoom()
        {
            InitializeComponent();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void UC_UpdateRoom_Load(object sender, EventArgs e)
        {
            query = "select * from rooms";
            DataSet ds = fn.getData(query);
            DataGridView1.DataSource = ds.Tables[0];
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if(txtRoomNo.Text != "" && txtType.Text != "" && txtBed.Text != "" && txtPrice.Text !="")
            {
                string roomno = txtRoomNo.Text;
                string type = txtType.Text;
                string bed = txtBed.Text;
                Int64 price = Int64.Parse(txtPrice.Text);

                query = "insert into rooms (roomNO, roomType, bed, price) values ('" + roomno + "','" + type + "','" + bed + "','" + price + "')";
                fn.setData(query, "Room Added.");

                UC_UpdateRoom_Load(this, null);
            }
            else
            {
                MessageBox.Show("Fill all fields.", "Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}```

運行上面的代碼會返回以下錯誤:

警告:拋出異常:System.Data.dll 中的“System.Data.SqlClient.SqlException”附加信息:無法將值 NULL 插入列“roomID”,表“myHotel.dbo.rooms”; 列不允許空值。 插入失敗。 該語句已終止。

如何解決?

這是因為表中的roomID列。 如果您希望在手動插入新行時自動遞增,則必須在表定義中將其定義為自動遞增。

您的查詢有異常,因此您必須先解決,但在插入數據后刷新 datagridview,代碼應該是

UC_UpdateRoom_Load(sender, e);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM