在表单close事件中从SQL更新datagridview

时间:2014-04-01 16:04:11

标签: c# datagridview

我有一个带有从SQL数据库更新的dataGridView1的表单。

我想要做的是:当用户按下关闭按钮时我正在检查一个变量,如果条件为真,那么我取消关闭(e.Cancel = true;)并且我想显示一些数据数据网格。

无论我做什么,网格都不会更新。我正在调用一个" private void update()"从SQL更新网格,但在我取消表单关闭事件后,它似乎无法正常工作。

我尝试刷新表单,刷新数据网格没有结果。

在form_Close完成后,datagrid为空,如果我按下一个调用相同的按钮" private void update()"它工作正常,数据显示在数据网格中。

感谢您的帮助。

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表:

screenshot

这是我的datagrid的数据源:

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试在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();
        }
    }
}

答案 1 :(得分:0)

我找到了这个问题。 看起来这是我的错误,我仍然不知道为什么不按照它的方式工作,但知道原因。

我正在使用代码从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()时,它可以正常工作。当我调用它时,即使它运行没有错误也不会刷新网格。

按下关闭按钮时是否会切断我的连接?我认为这是另一个问题,这里不是主题。