美好的一天,
我现在正在做的是,我有一个foreach循环,我将通过一个包含服务器列表的文件。每次它通过它从一个文本文件提供的列表中查询不同的服务器。结果显示在datagridview中。但是现在每次查询新服务器时,它都会覆盖datagridview中已有的数据。我试图合并数据表,但它不起作用。有什么想法吗?
try
{
String select = "select @@servername as Servername, @@servicename as Instance,SERVERPROPERTY('productversion') as Version, SERVERPROPERTY ('productlevel') as Level, SERVERPROPERTY ('edition') as Edition";
cnn.Open();
// MessageBox.Show ("Connection Open ! ");
MessageBox.Show("Connection established");
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dataGridView.DataSource = table;
table.Merge(table);
cnn.Close();
//PaintRows();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " + ex);
}
答案 0 :(得分:0)
问题是你需要附加到你的表中,但是你在每次循环迭代中都会创建一个新的。
我要做的是:创建一个获取目标表变量的方法(因此在每个调用中它都是相同的)。
大纲:
**** This code is somewhere to fill the table ****
DataTable table = new DataTable();
foreach (line in file)
{
// Create connection to new server
cnn = ...;
// Append the results to the existing table
AppendSqlResults(table, cnn);
}
// Set the source AFTER collecting all the data
dataGridView.DataSource = table;
**** This method appends the data to the table ****
public void AppendSqlResults(DataTable table, SqlConnection cnn)
{
cnn.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
cnn.Close();
}