簡體   English   中英

在窗體關閉事件中從SQL更新datagridview

[英]Update datagridview from SQL in the form close event

我有一個帶有從SQL數據庫更新的dataGridView1的表單。

我想做的是:當用戶按下“關閉”按鈕時,我正在檢查一個變量,如果條件為true,則取消關閉(例如:Cancel = true;),並且我想在數據網格中顯示一些數據。

無論我做什么,網格都不會更新。 我正在調用“ private void update()”來從SQL更新網格,但是在取消表單關閉事件后,它似乎不起作用。

我嘗試刷新表格,刷新數據網格,但沒有結果。

在form_Close甚至完成之后,並且datagrid為空,如果我按下一個調用相同“ private void update()”的按鈕,它將起作用,並且數據將顯示在datagrid中。

謝謝您的幫助。

EDIT1:為您提供更多詳細信息

我在FormClosing上嘗試了代碼,但沒有結果。 我使用的代碼是:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        getdata_fromSQL();//this private void gets some data from sql into the datagrid

        if (dataGridView1.RowCount > 0)//check if i have at least one row retreved
        {
            // Cancel the Closing event and tell the user
            MessageBox.Show("Please check the data before leaving.");
            e.Cancel = true;
            getdata_fromSQL();// retrieve the data again for the user to see (this part is not working
        }
    }

這就是檢索數據的方式。

    private void getdata_fromSQL()
    {
      SqlConnection con = new SqlConnection("connection string"); //defining connection
      con.Open(); 
      string sql_command = "Select * from Test_Table where [Check] is null";
      SqlCommand command = new SqlCommand(sql_command, con); // defining the command
      DataSet set = new DataSet("SQL_table");
      SqlDataAdaptersda = new SqlDataAdapter(command); //defining the adapter and make it accept changes
      sda.AcceptChangesDuringFill = true; 
      sda.AcceptChangesDuringUpdate = true;
      set.Clear(); //just to make sure my adapter is empty
      cmdBuilder = new SqlCommandBuilder(sda); //creating the command builder so I can save the changes
    sda.Fill(set, "SQL_table");  // fill the dataset
    dataGridView1.DataSource = set; 
    dataGridView1.DataMember = "SQL_table"; //fill datagrid
    dataGridView1.CellValueChanged -= dataGridView1_CellValueChanged;
    dataGridView1.CellValueChanged += dataGridView1_CellValueChanged; //look for cell value changed (I am using this in other scope)
    }

在取消關閉並嘗試再次更新數據網格后,它仍然為空。

EDIT2:@Gami

您的代碼執行此操作:

     private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (i == 1)
        {
            MessageBox.Show("Hello");
            e.Cancel = true;
            getRefresh();
        }
    }

您的刷新是這樣的:

     private void getRefresh()
    {
        SqlConnection con = new SqlConnection(@"user id=testuser;" +
                                   "password=testpass;Data Source=SERVER;" +
            //                           "Trusted_Connection=yes;" +
                                   "Initial Catalog=Partner_database; " +

                                   "connection timeout=30"); //defining connection
        con.Open();
        SqlCommandBuilder cmdBuilder;
        string sql_command = "Select * from Test_table where [Check] is null";
        SqlCommand command = new SqlCommand(sql_command, con); // defining the command
        DataSet set = new DataSet("SQL_table");
        SqlDataAdapter sda = new SqlDataAdapter(command); //defining the adapter and make it accept changes
        sda.AcceptChangesDuringFill = true;
        sda.AcceptChangesDuringUpdate = true;
        set.Clear(); //just to make sure my adapter is empty
        cmdBuilder = new SqlCommandBuilder(sda); //creating the command builder so I can save the changes
        sda.Fill(set,"SQL_table");  // fill the dataset
        dataGridView1.DataSource = set;
        dataGridView1.DataMember = "SQL_table"; //fill datagrid

    }

我的代碼是上面的代碼。 我們都使用FormClosing事件,我們都取消關閉過程,然后調用刷新。

這是SQL表:

屏幕截圖

這是我的數據網格的數據源:

在此處輸入圖片說明

嘗試在Form1_FormClosing()事件中編寫代碼

例子是

namespace canceldemo
{
    public partial class Form1 : Form
    {
        int i = 1;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (i == 1)
            {
                MessageBox.Show("Hello");
                e.Cancel = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text = (i+10).ToString();
        }
    }
}

我發現了問題。 看來這是我的錯,但我仍然不知道為什么不按原樣工作,但知道原因。

我正在使用代碼從Windows獲取登錄的用戶名,並且當我過濾SQL表時,也會對用戶進行過濾。

這是檢索用戶的代碼:

    private string getUserDisplayName()
    {
        var username = new StringBuilder(1024);
        uint userNameSize = (uint)username.Capacity;

        // try to get display name and convert from "Last, First" to "First Last" if necessary
        if (0 != GetUserNameEx(3, username, ref userNameSize))
            return Regex.Replace(username.ToString(), @"(\S+), (\S+)", "$2 $1");

        // get SAM compatible name <server/machine>\\<username>
        if (0 != GetUserNameEx(2, username, ref userNameSize))
        {
            IntPtr bufPtr;
            try
            {
                string domain = Regex.Replace(username.ToString(), @"(.+)\\.+", @"$1");
                DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain);
                DomainController dc = DomainController.FindOne(context);

                if (0 == NetUserGetInfo(dc.IPAddress,
                                        Regex.Replace(username.ToString(), @".+\\(.+)", "$1"),
                                        10, out bufPtr))
                {
                    var userInfo = (USER_INFO_10)Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_10));
                    return Regex.Replace(userInfo.usri10_full_name, @"(\S+), (\S+)", "$2 $1");
                }
            }
            finally
            {
                NetApiBufferFree(out bufPtr);
            }
        }

        return String.Empty;
    }

在我的FormClosing塊中,我稱這個私有的void並將其用作sql的過濾器。

    user_name = getUserDisplayName();
    string sql_command = "Select * from Test_table where [Check] is null and [User Name] = '" + user_name + "'";

刪除getUserDisplayName()時,它可以工作。 當我調用它時,即使它沒有錯誤運行,它也不會刷新網格。

當我按下關閉按鈕時,會斷開我的連接嗎? 我認為這是另一個問題,這里不合主題。

暫無
暫無

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

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