我有这样的数据表
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);
}
当我点击button12时它很好地更新,但我想让它变得更好,并试图让它自动更新,所以我把她移到了
public partial class Form1 : Form
{ // same exact table
}
那样表格可以在1个范围内访问,也许,也许,只是可能,它会更新每个动作..它没有结果确定,因为当我更改变量readG.Text时,表格,因为它花了早期计划的价值,没有更新价值。
我想创建一个更新表的按钮,并重复行和列“添加”,但有没有更简单,更有效的方法呢?比如,“每次行动,重装价值”?
另外一个问题,如果我创建其他表单,它显示当前数据表,如何创建我刚刚创建的表,保持表格1?
(我对get,set一无所知,所以如果有人能用一种简单的方式解释这些“命令”,我将非常感激)
答案 0 :(得分:1)
如果我理解你的问题,这可能是实现你所需要的一种方式:
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);
}
}
}