使用CheckedListBox

时间:2019-07-05 14:33:25

标签: c# .net winforms datagridview

我正在开发一个处理SQL Server数据库的Windows窗体应用程序。当我单击一个填充有所有表的组合框时,我将选中表中的每一列添加到checkedlistbox中,然后我将检查下一列消失。我被困在这里。

private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        var tableName = comboBox1.SelectedItem;

        SqlDataAdapter sqlDa = new SqlDataAdapter($"SELECT * FROM {tableName}", form1.conn = new SqlConnection($"Server = {form1.ServerBox.Text }; Database = { form1.DBBox.Text}; Trusted_Connection = True"));

        DataTable dataTable = new DataTable();
        sqlDa.Fill(dataTable);

        string comboQuery = $"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'{tableName}'";

        using (form1.conn = new SqlConnection($"Server = {form1.ServerBox.Text }; Database = { form1.DBBox.Text}; Trusted_Connection = True"))
        {
            form1.conn.Open();

            using (SqlCommand cmd = new SqlCommand(comboQuery, form1.conn))
            {
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    checkedListBox1.Items.Clear();

                    while (reader.Read())
                    {
                        checkedListBox1.Items.Add((string)reader["COLUMN_NAME"]);
                    }
                }
            }

            form1.conn.Close();
        }

        dataGridView1.DataSource = dataTable;
}

谢谢您的投入!

2 个答案:

答案 0 :(得分:5)

当列在DataGridView中时,您无需再次从SQL Server加载它们,并且如其他答案所示,您可以从DataGridView获取列名。

要将列添加到CheckedListBox,我更喜欢使用DataSourceDisplayMemberValueMemberHeaderText中显示列CheckedListBox ,同时可以访问其名称以在DataGridView中找到它们。

然后,根据项目对应列的可见性设置项目的初始检查状态。

然后我处理ItemCheck事件,并根据选中的项目查找列名,并根据新的检查状态设置列的可见性:

//Add the columns to checked list box
var columns = dataGridView1.Columns.Cast<DataGridViewColumn>()
    .Select(x => new { x.Name, x.HeaderText }).ToList();
checkedListBox1.DataSource = columns;
checkedListBox1.ValueMember = "Name";
checkedListBox1.DisplayMember = "HeaderText";

//Set initial check state based on columns visibility
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    dynamic item = checkedListBox1.Items[i];
    checkedListBox1.SetItemChecked(i, dataGridView1.Columns[(string)item.Name].Visible);
}

//Hanlde ItemCheck event
checkedListBox1.ItemCheck += (obj, args) =>
{
    dynamic item = checkedListBox1.Items[args.Index];
    var visible = args.NewValue == CheckState.Checked ? true : false;
    dataGridView1.Columns[(string)item.Name].Visible = visible;
};

enter image description here

以防您有兴趣使用ContextMenuStrip

//Add the columns to context menu strip
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
    var item = (ToolStripMenuItem)contextMenuStrip1.Items.Add(c.HeaderText);
    item.Tag = c.Name;
    item.Checked = c.Visible;
    item.CheckOnClick = true;

    //Hanlde CheckStateChanged event of context menu strip items
    item.CheckStateChanged += (obj, args) =>
    {
        var i = (ToolStripMenuItem)obj;
        dataGridView1.Columns[(string)i.Tag].Visible = i.Checked;
    };
}

//Show context menu strip on right click on data grid veiw header
dataGridView1.CellMouseClick += (obj, args) =>
{
    if (args.RowIndex == -1 && args.Button == MouseButtons.Right)
        contextMenuStrip1.Show(Cursor.Position);
};

enter image description here

答案 1 :(得分:1)

您可以先填充CheckedListBox,如下所示:

checkedListBox1.Items.Clear   
checkedListBox1.Items.AddRange(dataGridView1.Columns.Cast<DataGridViewColumn>()
                                                    .Select(x => x.Name)
                                                    .ToArray());

for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    checkedListBox1.SetItemChecked(i, true);
}
checkedListBox1.CheckOnClick = true;

现在,您可以像这样对checkedListBox1_SelectedIndexChanged事件进行编码:

for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    dataGridView1.Columns[i].Visible =
       checkedListBox1.GetItemCheckState(i) == CheckState.Checked;
}

更新,Reza发现了ItemCheck事件;不知道我怎么想念它;-)。这显然要好得多,因为它不需要遍历所有项目。