How to create a tab control with a dynamic number of tabs in Visual Studio C#?
I\'ve got a database with a table customers
. I need to create a form that
You can generate dynamic tabs with the existing TabControl. Here is an example of how it can be done in a somewhat sort of pseudo code form...
TabControl tabControl = new TabControl();
tabControl.Dock = DockStyle.Fill;
foreach (Char c in lastNameList)
{
TabPage tabPage = new TabPage();
tabPage.Text = c.ToString();
DataGrid grid = new DataGrid();
grid.Dock = DockStyle.Fill;
grid.DataSource = dataForTheCurrentLoop;
tabPage.Controls.Add(grid);
tabControl.Controls.Add(tabPage);
}
this.Controls.Add(tabControl);
It sounds like the best route for you would be to create your own custom tab control class. It could inherit from tab control for the bulk of its functionality and properties for the datagrid and whatever else custom you need. Then when you get your customers, you can create a tab for each letter you need and setup the corresponding properties.
I don't remember the specifics now. But just look at the code in the XXX.designer.cs file for a form you have that contains a tab control. There you'll see the code generated to add a new tab. Just replicate those lines, you can add a new tab whenever you want.
You would add the code to generate the tabs where you determine what letters are required to be shown, probably when you either retrieve the data or in the form's OnLoad()
method. You should be able to dynamically add/remove tabs from the built-in tab control. You can check the designer code for some idea how to do it, or the docs.
Note that it isn't necessarily a good idea to add a separate tab for each character. 26 tabs (which will happen when your database gets reasonably large) is a pretty awful number of tabs for someone to look through-- it won't necessarily make things faster at all.
Instead, consider providing a dynamic filtering mechanism, similar to the search box on Vista's start menu. Your user can type a single character (assuming you aren't writing some sort of kiosk or touch-screen-only software) and zoom immediately to the relevant names. This would work ideally with a ListView
in List or Details mode.