[英]DataTable Not Being Updated With Newest Data
I have a windows form with a combo box that allows a user to select from the drop down list then press a button, which will query an API then populate a SQL Server Table with data, then format the data and display 3 fields on a datagridview. 我有一个带组合框的Windows窗体,允许用户从下拉列表中选择然后按一个按钮,这将查询API,然后用数据填充SQL Server表,然后格式化数据并在datagridview上显示3个字段。 Then the user has the option to discard the data or to export to a csv. 然后,用户可以选择丢弃数据或导出到csv。
Well this process works perfect for one run, but once you attempt to export a second set of information to a csv the C# variables/datatable retains the information from the first run. 很好,此过程非常适合一次运行,但是一旦您尝试将第二组信息导出到CSV,C#变量/数据表将保留第一次运行的信息。 (I have verified server side everything is populated as it should be) (我已经验证了服务器端的所有内容都已经填充了)
I step through my code and debug and have isolated the issue down to the fact that this line of code Form1.dtEmpNames = Form1.allEmps.DefaultView.ToTable(true, "Name");
我逐步检查代码并进行调试,并将问题归结为以下事实:代码行Form1.dtEmpNames = Form1.allEmps.DefaultView.ToTable(true, "Name");
never updates to the new name that is selected. 从不更新为所选的新名称。 It keeps the first name. 它保留名字。
namespace Be1ng
{
public partial class Form1 : Form
{
public static DataTable allEmps = new DataTable();
public static DataTable dtEmpNames = new DataTable();
public void btnPush_Click()
{
allEmps.Clear();
string query = "Select * from test";
SqlConnection conn = new SqlConnection(@"Data Source=Server info;Initial Catalog=DB;User Id=user;Password=pwd;");
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(allEmps);
conn.Close();
Form2 f2 = new Form2();
f2.ShowDialog();
}
}
}
namespace Be1ng
{
public partial class Form2 : Form
{
Private void Form2_Load(object sender, EventArgs e)
{
Form1.dtEmpNames = Form1.allEmps.DefaultView.ToTable(true, "Name");
}
}
}
Away from the computer so this is untested, and use more meaningful DataTable names, but this should at least provide an example of doing such... 远离计算机,因此未经测试,并使用更有意义的DataTable名称,但这至少应提供执行此操作的示例...
//Form1 - declare the DataTable in the method and pass it to Form2 load
public void btnPush_Click()
{
DataTable allEmps = new DataTable();
//Query your server here
conn.Close();
//pass the datatable in the call for the form
Form2 f2 = new Form2(allEmps);
f2.ShowDialog();
}
//Then in the form2 load create a new constructor that accepts the DataTable
private DataTable dtpassed = new DataTable();
private DataTable dtallemps = new DataTable();
public Form2(DataTable allemps)
{
dtallemps = dtpassed;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
dtallemps = dtpassed.DefaultView.ToTable(true, "Name");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.