在 C# Winform 程序中,可以通过以下步骤使用 DataGridView 控件实时显示 SQL Server 中的数据:
csharp
string connStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True";
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
csharp
string sql = "SELECT * FROM table1";
SqlCommand cmd = new SqlCommand(sql, conn);
csharp
SqlDataReader dr = cmd.ExecuteReader();
csharp
while (dr.Read())
{
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView1);
row.Cells[0].Value = dr["id"];
row.Cells[1].Value = dr["name"];
// ...
dataGridView1.Rows.Add(row);
}
csharp
Timer timer = new Timer();
timer.Interval = 1000; // 1 秒
timer.Tick += (s, e) =>
{
// 执行查询并填充 DataGridView
};
timer.Start();
这样,DataGridView 就可以每隔 1 秒自动去数据库查询最新数据并更新显示,实现实时显示数据的效果。
对于如何实现和使用DataGridView控件实时显示SQL Server数据库中特定数据的问题,可以按照以下步骤进行操作:
创建Winform程序界面,并添加DataGridView控件。
在程序中使用SqlConnection对象连接SQL Server数据库,并编写查询语句。
用SqlDataAdapter适配器将查询结果填充到DataSet对象中,例如:
string sql = "SELECT * FROM employee";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
DataSet dataset = new DataSet();
adapter.Fill(dataset, "employee");
dataGridView1.DataSource = dataset.Tables["employee"];
然后在需要实时更新数据的地方,例如点击按钮时,可以重新查询数据库,将结果再次填充到DataSet中,并将DataGridView的数据源指向新的DataSet,以实现实时更新数据的效果。
修改当前选中行的数据可以按照如下步骤进行操作:
在form1中编写代码,获取当前选中的行的ID,然后创建并显示form2。例如:
if (this.dataGridView1.SelectedRows.Count > 0)
{
int index = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value.ToString());
ChangeForm changeForm = new ChangeForm(index.ToString());
changeForm.ShowDialog();
}
else
{
MessageBox.Show("请先选中再操作");
}
public ChangeForm(string id)
{
InitializeComponent();
string sql = "SELECT * FROM employee WHERE id=@id";
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddWithValue("@id", id);
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
textBox1.Text = reader["name"].ToString();
textBox2.Text = reader["age"].ToString();
textBox3.Text = reader["sex"].ToString();
reader.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string sql = "UPDATE employee SET name=@name, age=@age, sex=@sex WHERE id=@id";
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddWithValue("@name", textBox1.Text);
sqlCommand.Parameters.AddWithValue("@age", textBox2.Text);
sqlCommand.Parameters.AddWithValue("@sex", textBox3.Text);
sqlCommand.Parameters.AddWithValue("@id", id);
int result = sqlCommand.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("修改成功!");
}
}
以上是关于如何实现和使用DataGridView控件展示SQL Server数据库中特定数据以及修改数据的具体指导。