上述代码是选择了listbox的item才会再datagridview中显示线管内容 现在改为当listBox1内容有变化时 把listBox1的所有内容都查询到datagridview1中
您可以使用以下代码来实现当listBox1内容有变化时,将listBox1的所有内容查询到dataGridView1中:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// 清空dataGridView1的内容
dataGridView1.Rows.Clear();
// 遍历listBox1中的所有项
foreach (var item in listBox1.Items)
{
// 查询item对应的内容,并添加到dataGridView1中
string query = "SELECT * FROM your_table WHERE column_name = @item";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@item", item.ToString());
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 将查询结果添加到dataGridView1中
dataGridView1.Rows.Add(reader["column1"], reader["column2"], ...);
}
}
}
}
}
请将 your_table 替换为您要查询的表名,column_name 替换为您要根据哪一列的值进行查询的列名,column1, column2, ... 替换为您要显示在dataGridView1中的列名。
此代码将在 listBox1 的 SelectedIndexChanged 事件中触发查询动作,并将查询到的结果添加到 dataGridView1 中。每次更改 listBox1 的内容,都会重新查询和显示所有项的内容
原文地址: https://www.cveoy.top/t/topic/iKMv 著作权归作者所有。请勿转载和采集!