【问题标题】:c# Ask to save changes before selecting another item in listboxc#在选择列表框中的另一个项目之前要求保存更改
【发布时间】:2019-03-08 12:29:51
【问题描述】:

我想集成一个自动检查功能,以防止用户忘记保存更改,并带有文本框“您要保存更改吗”是-否

如果是 -> 保存 如果没有 -> 返回

这是我没有检查的代码

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
    OleDbConnection conn;

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        conn = new 
        OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data 
        Source=" + @Application.StartupPath + "\\Database1.mdb");
        fill_lb();
    }
    private void fill_lb()
    {
        listBox1.Items.Clear();
        if (conn.State != ConnectionState.Open) { conn.Close(); 
        conn.Open(); }
        OleDbCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM [table1] ORDER BY firstn";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        da.Fill(dt);
        foreach (DataRow dr in dt.Rows)
        {
            listBox1.Items.Add(dr["firstn"].ToString());
        }
        conn.Close();
    }
    private void listBox1_SelectedIndexChanged(object sender, 
    EventArgs e)
    {
        textBox_fn.Text = string.Empty;
        textBox_ln.Text = string.Empty;

        if (conn.State != ConnectionState.Open) { conn.Close(); 
        conn.Open(); }
        OleDbCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + 
        listBox1.SelectedItem.ToString() + "'";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        da.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            textBox_fn.Text = dr["firstn"].ToString();
            textBox_ln.Text = dr["lastn"].ToString();
        }
        conn.Close();
    }

    private void button_savenew_Click(object sender, EventArgs e)
    {
        if (conn.State != ConnectionState.Open) { conn.Close(); 
        conn.Open(); }
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = conn;
        cmd.CommandText = "INSERT INTO [table1] ([firstn],[lastn]) 
        values ([@firstn],[@lastn])";

        cmd.Parameters.AddWithValue("@firstn", textBox_fn.Text);
        cmd.Parameters.AddWithValue("@lastn", textBox_ln.Text);
        cmd.ExecuteNonQuery();
        fill_lb();
        conn.Close();
    }

    private void button_modify_Click(object sender, EventArgs e)
    {
        if (conn.State != ConnectionState.Open) { conn.Close(); 
        conn.Open(); }
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = conn;
        cmd.CommandText = "UPDATE [Table1] SET [firstn]=[@firstn], 
        [lastn]=[@lastn] WHERE firstn = '" + 
        listBox1.SelectedItem.ToString() + "'";
        cmd.Parameters.AddWithValue("@firstn", textBox_fn.Text);
        cmd.Parameters.AddWithValue("@lastn", textBox_ln.Text);
        cmd.ExecuteNonQuery();
        fill_lb();
        conn.Close();
    }

    private void button_new_Click(object sender, EventArgs e)
    {
        textBox_fn.Text = string.Empty;
        textBox_ln.Text = string.Empty;
    }
  }
}

我做了什么没有成功:

    Bool modified = false

    private void  textBox_fn_TextChanged(object sender, EventArgs e)
    {
        modified = true;
    }

    private void textBox_ln_TextChanged(object sender, EventArgs e)
    {
        modified = true;
    }


    private void listBox1_SelectedIndexChanged(object sender, 
    EventArgs e)
    {
        if (modified.Equals(true))
        {
            DialogResult dialogr = MessageBox.Show("Do you want to 
            save change ?","", MessageBoxButtons.YesNo);
            switch (dialogr)
            {
                case DialogResult.Yes:
                    button_savenew.PerformClick();
                    modifie = false;
                    break;
                case DialogResult.No:
                    return;
            }
        }

        modified = false;
        textBox_fn.Text = string.Empty;
        textBox_ln.Text = string.Empty;

    }

这不起作用,因为每次我点击列表框时它都会要求保存

我能做什么?

【问题讨论】:

  • 也许您应该在表单的OnClosing 事件中而不是在列表的SelectedIndexChanged 中执行检查
  • 是的,我可以在 OnClosing 添加一个检查,但是,如果我正在编辑一个条目并且我错过了从列表框中单击另一个条目,我也想执行该检查。

标签: c# database winforms listbox


【解决方案1】:

我会考虑使用MessageBox。这将大大简化您尝试做的事情。在后台执行检查,如果他们没有保存,请执行以下操作:

        string message = "Are you sure you don't want to save?";
                       string caption = "Error Detected in Input";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result;

        // Displays the MessageBox.

        result = MessageBox.Show(message, "Are you Sure", buttons);

        if (result == System.Windows.Forms.DialogResult.Yes)
        {

            // Save file

        }
        if (result == System.Windows.Forms.DialogResult.No){
            this.Close();
        }

【讨论】:

    【解决方案2】:

    listBox1_SelectedIndexChanged 事件中删除关联代码并将button_modify_Click 添加到它的末尾。试试看:

    private  void Check()
    {
          if (modified.Equals(true))
            {
                DialogResult dialogr = MessageBox.Show("Do you want to 
                save change ?","", MessageBoxButtons.YesNo);
                switch (dialogr)
                {
                    case DialogResult.Yes:
                        button_savenew.PerformClick();
                        modifie = false;
                        break;
                    case DialogResult.No:
                        return;
                }
            }
    
            modified = false;
            textBox_fn.Text = string.Empty;
            textBox_ln.Text = string.Empty;
    }
    
     private void button_modify_Click(object sender, EventArgs e)
     {
            if (conn.State != ConnectionState.Open) { conn.Close(); 
            conn.Open(); }
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            cmd.CommandText = "UPDATE [Table1] SET [firstn]=[@firstn], 
            [lastn]=[@lastn] WHERE firstn = '" + 
            listBox1.SelectedItem.ToString() + "'";
            cmd.Parameters.AddWithValue("@firstn", textBox_fn.Text);
            cmd.Parameters.AddWithValue("@lastn", textBox_ln.Text);
            cmd.ExecuteNonQuery();
            fill_lb();
            Check(); //<--added here
            conn.Close();
    }
    

    【讨论】:

      【解决方案3】:

      在数据库更新后尝试重置modified,在button_modify_Click结束时

      【讨论】:

        【解决方案4】:

        我想我找到了使用 tag 属性完成这项工作的正确方法。

        首先我添加一个新的布尔值,它将检查我是否离开文本框

          bool left_txtbox = false; //when leaving textbox
        

        然后我将此代码添加到文本框的 Leave 属性中

         private void textBox_fn_Leave(object sender, EventArgs e)
            {
                name = listBox1.SelectedItem.ToString();
                textBox_fn.Tag = textBox_fn.Text;
                left_txtbox = true;
            }
        
            private void textBox_ln_Leave(object sender, EventArgs e)
            {
                name = listBox1.SelectedItem.ToString();
                textBox_ln.Tag = textBox_ln.Text;
                left_txtbox = true;
            }
        

        在列表框选择的索引更改上我在离开文本框时添加检查

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (left_txtbox == true) Check(); // if txtbox has been left, do the check
                textBox_fn.Text = string.Empty;
                textBox_ln.Text = string.Empty;
        
                if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
                OleDbCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + listBox1.SelectedItem.ToString() + "'";
                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                da.Fill(dt);
        
                foreach (DataRow dr in dt.Rows)
                {
                    textBox_fn.Text = dr["firstn"].ToString();
                    textBox_ln.Text = dr["lastn"].ToString();
                }
        
        
                conn.Close();
            }
        

        最后是检查本身,它将Tag与存储在DB中的值进行比较

         private void Check()
            {
        
                if (conn.State != ConnectionState.Open) { conn.Close(); conn.Open(); }
                OleDbCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM [table1] WHERE firstn='" + name + "'";
                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                da.Fill(dt);
        
                foreach (DataRow dr in dt.Rows)
                {
                    try // ignore null values
                    {
        
                        if (textBox_fn.Tag.ToString() != dr["firstn"].ToString()) { modified = true; }
                        if (textBox_ln.Tag.ToString() != dr["lastn"].ToString()) { modified = true; }
                    }
                    catch { }
        
                if (modified.Equals(true))
                {
                    DialogResult dialogr = MessageBox.Show("Do you want to save change ? ", "", MessageBoxButtons.YesNo);
                    switch (dialogr)
                    {
                        case DialogResult.Yes:
                            button_savenew.PerformClick();
                            modified = false;
                            break;
                        case DialogResult.No:
                            modified = false;
                            return;
                    }
                }
        
                modified = false;
        
            }
        

        我认为代码可以优化

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多