我有一个带有tabpages的TabControl,每个tabpages都有一个datagridview,它在运行时生成并在运行时再次与数据源绑定。这是执行此操作的代码:
foreach (string cat in category) //category is a list of categories I wish to make tabs for
{
TabPage page = new TabPage(cat);
DataGridView data = new DataGridView();
data.Name = "Data";
data.Location = new Point(1, 0);
data.AllowUserToDeleteRows = false;
data.ReadOnly = true;
data.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
data.MultiSelect = false;
//here load data for the datagridview
try
{
using (MySqlConnection connection = new MySqlConnection(Class1.connString))
{
string sql = "SELECT Code, `Problem Description` FROM problemcode WHERE Category = '" + cat + "' AND Type = 'Problem' ORDER BY `Problem Description`";
connection.Open();
using (MySqlCommand cmdSel = new MySqlCommand(sql, connection))
{
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmdSel);
da.Fill(dt);
data.DataSource = dt;
}
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Unable to load problem data.\n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
//here I add the datagridview to the tab
page.Controls.Add(data);
this.tabControl1.TabPages.Add(page);
data.CellDoubleClick += new DataGridViewCellEventHandler(data_CellDoubleClick);
data.CellEnter += new DataGridViewCellEventHandler(data_CellEnter);
}
为了便于讨论,我将从一个标签中讨论datagridview。我想在单击选项卡时访问此datagridview的数据源,但由于它是在运行时生成的,所以我这样做:
BindingSource bs = new BindingSource();
DataGridView selectedDtgv = new DataGridView();
if (tabControl1.SelectedTab.Controls.ContainsKey("Data")) //find datagridview named "Data"
{
selectedDtgv = (DataGridView)tabControl1.SelectedTab.Controls["Data"];
bs.DataSource = selectedDtgv.DataSource;
}
但是我的BindSource bs对象中没有数据。如果我做了像selectedDtgv.Rows.Count这样的东西,它给了我正确的行数,为什么它不给我DataSource?