【发布时间】:2019-08-24 08:11:16
【问题描述】:
我在处理作业/家庭作业中的问题时遇到了这个问题。我想将我的 SQL 数据库中的多个数据表加载到多个数据网格视图中,但是当我单击另一个选项卡(在 TabControl 上使用 SelectedIndexChanged)时,旧加载表的列仍然存在。我只希望每个选项卡都显示特定的表格(列)。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace assignment2Database
{
public partial class Form1 : Form
{
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
string str = @"Data Source=DESKTOP-S1O2044\SQLEXPRESS;Initial Catalog=ElectroShopDB;Integrated Security=True";
private void tabSupplier_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl.SelectedIndex == 0)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
else if (tabControl.SelectedIndex == 1)
{
connection = new SqlConnection(str);
connection.Open();
loadSupplier();
}
}
void loadCatalogue()
{
command = connection.CreateCommand();
command.CommandText = "select catalogueID,catalogueName from Catalogue";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvCatalogue.DataSource = table;
}
private void Form1_Load(object sender, EventArgs e)
{
connection = new SqlConnection(str);
connection.Open();
loadCatalogue();
}
void loadSupplier()
{
command = connection.CreateCommand();
command.CommandText = "select supplierID,supplierName from Supplier";
adapter.SelectCommand = command;
table.Clear();
adapter.Fill(table);
dgvSupplier.DataSource = table;
}
我希望在选项卡控件上的每个选项卡上触发 SelectedIndexChanged 事件时,前一个 datagridview 的旧列不会出现在新加载的 datagridview 上。或者我只想让每个单独的 datagridview 保存我的 SQL 数据库中的一个表。
【问题讨论】:
-
您应该为每个选项卡创建不同的数据表并填充相应的数据表并加载到网格中。
标签: c# sql-server datagridview relational-database