在每个动作上保持数据表的更新“;实时模式”/自动更新

本文关键字:更新 实时 模式 数据表 | 更新日期: 2023-09-27 17:59:03

我有一个类似的数据表

    private void button12_Click(object sender, EventArgs e)
    {   DataTable tableEC0 = new DataTable();
        tableEC0.Columns.Add("Nome", typeof(string));
        tableEC0.Columns.Add("valor", typeof(string));
        tableEC0.Rows.Add("G", readG.Text);
        tableEC0.Rows.Add("Q", readQ.Text);
        tableEC0.Rows.Add("W", readW.Text);
        tableEC0.Rows.Add("Tipodeverificacao", tipodeverificacao);
     }

当我点击按钮12时,它更新得很好,但我想让它变得更好,并试图让它自动更新,所以我把她调到

public partial class Form1 : Form
{ // same exact table
}

这样,表格就可以访问整个表格,也许,只是也许,它会在每次操作时更新。。结果不太好,因为当我把变量改为G时。文本,由于表采用了早期程序中的值,因此没有更新值。

我很难创建一个按钮来更新表,并重复行和列的"添加",但有更简单、更省时的方法吗?比如,"在每个操作中,重新加载值"?

还有一个问题,如果我创建了另一个表单,其中显示了当前的数据表,我如何使我刚刚创建的表在那里可以访问,并将表保持在表单1中?

(我对get、set一无所知,所以如果有人能用简单的方式解释这些"命令",我将非常感谢)

在每个动作上保持数据表的更新“;实时模式”/自动更新

如果我正确理解你的问题,这可能是实现你所需要的一种方法:

public partial class Form1 : Form
{ 
    DataTable tableEC0 = new DataTable(); // central table 
    public Form1()
    {
        InitializeComponent();
        // initialize your table with the columns needed
        tableEC0.Columns.Add("Nome", typeof(string));
        tableEC0.Columns.Add("valor", typeof(string));
        // hookup textbox
        readG.TextChanged += readG_TextChanged;
        readQ.TextChanged += readQ_TextChanged;
        readW.TextChanged += readW_TextChanged;
    } 
    // refactored to one call
    private void button12_Click(object sender, EventArgs e)
    {      
        UpdateAll();
    }
    // hookup this method to the TextBox_Changed event 
    private void readG_TextChanged(object sender, EventArgs e)
    {
        Update("G", (TextBox) sender);
    }
    private void readQ_TextChanged(object sender, EventArgs e)
    {
        Update("Q", (TextBox) sender);
    }
    private void readW_TextChanged(object sender, EventArgs e)
    {
        Update("W", (TextBox) sender);
    }
    // update all values
    private void UpdateAll()
    {
        Update("G", readG.Text);
        Update("Q", readQ.Text);
        Update("W", readW.Text);
        Update("Tipodeverificacao", tipodeverificacao);
    }
    // update from a textbox event
    private void Update(string key, TextBox txtBox)
    {
         Update(key, txtBox.Text);
    }
     // update (or insert in new) a row in your table
     private void Update(string key, string value)
     {
        // find a row
        var rows = tableEC0.Select(
                   String.Format("'Nome'='{0}'", key));
        if (rows.Length==1)  
        {
             // found, update
             rows[0]["valor"]= value;
        } 
        else if(rows.Length > 1)
        {
             throw new Exception("huh? too many rows found");
        }
        else
        {
             // not found, add
              tableEC0.Rows.Add(key, value);
        }
     }
}