c#在列表框中选择另一个项目之前要求保存更改

时间:2019-03-08 12:29:52

标签: c# database winforms listbox

我想集成一个自动检查功能,以防止用户忘记使用文本框保存所做的更改'是要否

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

这是我的代码,没有检查

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;

    }

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

我该怎么办?

4 个答案:

答案 0 :(得分:2)

我会考虑使用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();
        }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

在数据库更新后 Bitmap bmp = BitmapFactory.decodeFile(imagePath); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] imageByteArray = stream.toByteArray(); String encodedImageString = Base64.encodeToString(imageByteArray, Base64.DEFAULT); URL url = new URL(Config.CLOUD_VISION_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); con.setDoInput(true); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // Features JSON JSONObject featuresJson = new JSONObject(); featuresJson.put("type", "FACE_DETECTION"); featuresJson.put("maxResults", 1); JSONArray featuresJSONArray = new JSONArray(); featuresJSONArray.put(featuresJson); // Image JSON JSONObject imageJson = new JSONObject(); imageJson.put("content", encodedImageString); // Requests JSON JSONObject requestsJson = new JSONObject(); requestsJson.put("image", imageJson); requestsJson.put("features", featuresJSONArray); JSONArray requestsJSONArray = new JSONArray(); requestsJSONArray.put(requestsJson); JSONObject wholeRequest = new JSONObject(); wholeRequest.put("requests", requestsJSONArray); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(wholeRequest.toString()); out.flush(); out.close(); int response_code = con.getResponseCode(); Log.d("GCV Response Code", ""+response_code); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(""); String temp; while((temp = br.readLine()) != null) sb.append(temp); String response = sb.toString(); JSONObject responseJSONObject = new JSONObject(response); if (response_code == 200) { Log.d("GCV", "Successful response"); } JSONArray responsesArray = responseJSONObject.getJSONArray("responses"); JSONObject faceAnnotationsJson = responsesArray.getJSONObject(0); JSONObject annotedEmotionsJson = faceAnnotationsJson.getJSONArray("faceAnnotations").getJSONObject(0); return annotedEmotionsJson; 结束时尝试重置modified

答案 3 :(得分:0)

我认为我找到了使用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();
    }

最后检查本身,它将标记与存储在数据库中的值进行比较

 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;

    }

我认为代码可以优化