Adding quantity if the product is exist in the DataGridView - vb.net

Can someone help me with my problem?
The picture below shows the same item I inputted. What I want is I don't like to show duplicate items in DataGridView. If the same product record adds, then the new will not be showed, it just add the quantity when clicking the "Save" button. And I don't know how to code it I'm just new to vb.net. Can somebody help me how to do it?? It would be a big help for me if you do, thank you so much!
Below is my code for Save button:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
initializeCon()
Dim found As Boolean = False
If (DataGridView1.Rows.Count > 0) Then
For Each row As DataGridViewRow In DataGridView1.Rows
If (Convert.ToString(row.Cells(1).Value) = dtDate.Text) And (Convert.ToString(row.Cells(2).Value) = txtProductCode.Text) AndAlso
(Convert.ToString(row.Cells(3).Value) = txtProductName.Text) Then
row.Cells(4).Value = Convert.ToString(txtQuantity.Text + Convert.ToInt16(row.Cells(4).Value))
found = True
End If
Next
If Not found Then
cmd = New SqlCommand("INSERT INTO tbl_productOrders VALUES('" & txtID.Text & "','" & dtDate.Text & "','" & txtProductCode.Text & "','" & txtProductName.Text & "'," & txtQuantity.Text & ");", con)
cmd.ExecuteNonQuery()
clrtxt()
SaveMsg()
Getdata()
End If
End If
End Sub

this is an axample to avoid duplicates while adding rows
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim exist As Boolean = False, numrow As Integer = 0, numtext As Integer
For Each itm As DataGridViewRow In DataGridView1.Rows
If itm.Cells(0).Value IsNot Nothing Then
If itm.Cells(0).Value.ToString = TextBox1.Text Then
exist = True
numrow = itm.Index
numtext = CInt(itm.Cells(1).Value)
Exit For
End If
End If
Next
If exist = False Then
DataGridView1.Rows.Add(New String() {TextBox1.Text, TextBox2.Text})
Else
DataGridView1.Rows(numrow).Cells(1).Value = CInt(TextBox2.Text) + numtext
End If
End Sub

There are two aspects to improve your program.
1. Make comparing products better
Since you need to check individual properties to find equal product, the better way is to overload == operator along with implementing IEquatable interface. You can read more here. When you do this, you can compare products with == operator: if (product1 == product2) { }. In this case three properties are being compared. If they all are the same, then two products are equal.
2. Make adding products to DataGridView easier
In order to make adding products to DataGridView easier, you need to leverage the handy binding mechanism in Windows Forms, which appeared in .NET Framework 2.0 - BindingSource. It acts like a medium between your data and controls. In order to make this class usable, you need to use another handy class - BindingList. You feed BindingList to BindingSource and assign BindingSource to DataSource property of DataGridView. After that you work only with BindingList collection (adding/removing/editing) - and all the propagation is done by BindinSource.
To summarize, here is the explanation and full code. Here you can download the project itself.
When you add product, the code first checks whether such product already exists in DataGridView (Add product button). Do note that we don't work with DataGridView directly - we work only with the collection. Thanks to enhancements, we can use LINQ here. If the product is not found, we add it to collection. If it's found, we just update the quantity.
If you need to update selected product data (Change quantity button), you only need to retrieve it from selected rows and use BoundDataItem - this is where our product is located. Then just update properties of product you need.
If you need to remove product (Delete product button), retrieve it from selected row and delete it from the collection.
Important! Do not forget to call Refresh() method on DataGridView after all taken actions in order to see the changes.
namespace WinFormsApp
{
public partial class Root : Form
{
private BindingList<Product> list = null;
private BindingSource bindingSource = null;
public Root() => InitializeComponent();
private void OnFormLoaded(object sender, EventArgs e)
{
// Our collection holding products
list = new BindingList<Product>();
// I've set up columns manually (with applied binding),
// so switch generating columns off.
dataGrid.AutoGenerateColumns = false;
// Disable adding new row
dataGrid.AllowUserToAddRows = false;
// Create our medium between grid and collection
bindingSource = new BindingSource { DataSource = list };
// Set binding
dataGrid.DataSource = bindingSource;
}
private void OnAddRecord(object sender, EventArgs e)
{
// Create new product
var new_product = new Product
{
Date = dtPicker.Value.ToShortDateString(),
Code = txtCode.Text,
Name = txtName.Text,
Quantity = npQuantity.Value
};
// No need to check individual properties here
// as == and IEquatable will do all the work.
// We can safely use LINQ here.
var p = list.FirstOrDefault(x => x == new_product);
if (p == null)
{
// Product is not found. Add it to list.
list.Add(new_product);
}
else
{
// Product is found. Update quantity.
p.Quantity += new_product.Quantity;
}
dataGrid.Refresh(); //Required to reflect changes
}
private void OnChangeQuantity(object sender, EventArgs e)
{
// Change quantity here.
var product = GetProduct();
if (product != null)
{
// Update product's quantity.
product.Quantity *= 2;
// Do not forget to refresh grid.
dataGrid.Refresh();
}
}
private void OnDeleteProduct(object sender, EventArgs e)
{
// Delete product here.
var product = GetProduct();
if (product != null)
{
// We need to delete product only from collection
list.Remove(product);
// Do not forget to refresh grid
dataGrid.Refresh();
}
}
// Retrieve product from selected row.
private Product GetProduct() =>
dataGrid.SelectedCells.Count == 0 ?
null :
dataGrid.SelectedCells[0].OwningRow.DataBoundItem as Product;
}
class Product : IEquatable<Product>
{
public string Date { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal Quantity { get; set; }
// Overload == operator
public static bool operator ==(Product firstProduct, Product secondProduct)
{
// Check for null on left side.
if (Object.ReferenceEquals(firstProduct, null))
{
if (Object.ReferenceEquals(secondProduct, null))
{
// null == null = true.
return true;
}
// Only the left side is null.
return false;
}
// Equals handles case of null on right side.
return firstProduct.Equals(secondProduct);
}
// Overload != operator (required when overloading == operator)
public static bool operator !=(Product firstProduct, Product secondProduct) =>
!(firstProduct == secondProduct);
// Implementing IEquatable<T> interface
public bool Equals(Product other)
{
// If 'other' is null, return false.
if (Object.ReferenceEquals(other, null))
{
return false;
}
// Optimization for a common success case.
if (Object.ReferenceEquals(this, other))
{
return true;
}
// If run-time types are not exactly the same, return false.
if (this.GetType() != other.GetType())
{
return false;
}
// Return true if the fields match.
return
Date == other.Date &&
Code == other.Code &&
Name == other.Name;
}
public override bool Equals(object obj) => this.Equals(obj as Product);
public override int GetHashCode() =>
Date.GetHashCode() + Code.GetHashCode() + Name.GetHashCode();
// Optional. For debugging purposes.
public override string ToString() =>
$"Date: {Date}, Code: {Code}, Name: {Name}, Quantity: {Quantity}";
}
}

Related

Insert in nested field

I'm a new user in LINQ to SQL and I have some problems using it.
I've used LINQ to SQL Designer and I have created my classes, mapped on the DB tables.
In particular, I have one class, named voice:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.voce")]
public partial class voce : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _id_voce;
... other private fields;
private int _category;
private EntityRef<category> _category1;
public voce()
{
this._riepilogo = new EntitySet<riepilogo>(new Action<riepilogo>(this.attach_riepilogo), new Action<riepilogo>(this.detach_riepilogo));
this._hera = default(EntityRef<hera>);
this._category1 = default(EntityRef<category>);
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id_voce", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int id_voce
{
get
{
return this._id_voce;
}
set
{
if ((this._id_voce != value))
{
this.Onid_voceChanging(value);
this.SendPropertyChanging();
this._id_voce = value;
this.SendPropertyChanged("id_voce");
this.Onid_voceChanged();
}
}
}
......
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_category", DbType="Int NOT NULL")]
public int category
{
get
{
return this._category;
}
set
{
if ((this._category != value))
{
if (this._category1.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OncategoryChanging(value);
this.SendPropertyChanging();
this._category = value;
this.SendPropertyChanged("category");
this.OncategoryChanged();
}
}
}
As you can see, voce class has a field named category that refers to a table named category.
When I add a new voce to my database, I create a new voce istance and, using the DataContext, i simply add it, using:
voce v = new voce(){...field, category1 = //create or retrieve category};
In particular, the category field is retrieved from the DB if already exists or, if not, it is inserted, before I insert the voice.
The problem is that when I add the voice in the database:
datacontext.InsertOnSubmit(v);
datacontext.SubmitChanges();
it inserts the category again, failing with the unique contraint.
How can I add a voice without adding every nested object?
Thank you and sorry for my bad English.
internal category GetCategoryFromDescription (string desc, Utility.VOICE_MODALITY mode)
{
bool type = mode == Utility.VOICE_MODALITY.ENTRATA ? true : false;
var query = from cat in dc.category
where cat.description == desc && cat.type == type
select cat;
if (query.Count() == 0)
{
category newC = new category() { description = desc };
dc.category.InsertOnSubmit(newC);
dc.SubmitChanges();
return newC;
}
else
return query.Single();
}

Razor default for dropdown box

I have a drop down list written in Razor for a MVC app I am working on as:
#Html.DropDownList("BillId", "")
However the user does not have to select anything according to the logic of my program (the list is populated with 'Bill' objects in my controller). If they do not select any thing I get an error
The ViewData item that has the key 'BillId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
How do I write a statement in Razor to return a BillId of 0 if nothing is selected?
I am not sure of the syntax as I have a background in straight java and VB but something alongs the line of
If DropdownBox.SelectedIndex = 0
Else
BillId = DropdownBox.SelectedIndex
End
Controller as follows:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Dim BillList = New List(Of Bill)()
Dim BillQuery = From s In db.Bills
Select s
BillList.AddRange(BillQuery)
ViewBag.BillIdList = New SelectList(BillList, "BillId", "BillDate")
ViewBag.BillId = New SelectList(BillList, "BillId", "BillDate")
Return View(job)
End Function
The POST function for create is as below:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
db.Jobs.Add(job)
db.SaveChanges()
Dim customer As Customer = db.Customers.Find(job.CustomerId)
Dim customerNumber As String = customer.CustCellphone.ToString()
Dim messageSender As SendMessage = New SendMessage
Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
messageSender.SendMessage(smsMessage, customerNumber)
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
Return View(job)
End Function
EDIT
I was wondering too how this is passed back as in the POST I may be able to check for a 'null'? However I feel the problem may be the moment the submit button is pressed
In your POST controller action you forgot to populate the ViewCrap (oops, I meant ViewBag) before returning the view:
<HttpPost()>
Function Create(job As Job) As ActionResult
If ModelState.IsValid Then
...
End If
' Here you must populate the ViewCrap before returning the view the same
' way you did in your GET action because your view depend on it
Dim BillQuery = From s In db.Bills
Select s
ViewBag.BillId = New SelectList(BillQuery.ToList(), "BillId", "BillDate")
Return View(job)
End Function
But I would hyper strongly recommend you to use view models and forget about the existence of the ...... (the word that I don't want to pronounce).
UPDATE:
Now let's look at the correct way to implement this (which is by using view models). A view model is a class that you should define for each of your views and which will represent its specific requirements. So from what you have said in the comments section to my answer you want to have a dropdown list in your view where the user has to select a bill from a dropdown and which is required.
So let's roll the view model:
public class JobViewModel
{
[Required(ErrorMessage = "Please select a bill")]
[Display(Name = "Bill")]
public int? SelectedBillId { get; set; }
public IEnumerable<SelectListItem> Bills
{
get
{
return db.Bills.ToList().Select(x => new SelectListItem
{
Value = x.BillId.ToString(),
Text = x.BillDate.ToString()
});
}
}
public int CustomerId { get; set; }
... here you could put any other properties that you want
to display on the view, things like JobId, ...
}
then we define our controller with the 2 actions:
public ActionResult Create(int id)
{
var model = new JobViewModel
{
CustomerId = id
};
return View(model);
}
[HttpPost]
public ActionResult Create(JobViewModel model)
{
if (ModelState.IsValid)
{
// Using AutoMapper here to map between the domain model
// and the view model (http://automapper.org/)
var job = Mapper.Map<JobViewModel, Job>(model);
// Now call your service layer to do the necessary processings
// on this job domain model including saving the job and sending
// messages and stuff. This avoids polluting your controller with
// business logic code which belongs to your service layer
ServiceLayer.ProcessJob(job);
return RedirectToAction("AddService", "RequestedService", new { id = job.JobId });
}
return View(model);
}
and finally you will have a corresponding view which will be strongly typed to the view model:
#model JobViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.SelectedBillId)
#Html.DropDownListFor(x => x.SelectedBillId, Model.Bills, "-- select --")
#Html.ValidationMessageFor(x => x.SelectedBillId)
</div>
... some other input fields
<p><button type="submit">OK</button></p>
}
And now, as promised in the comments section let me show what I dubbed the absolute pornographic approach to solve this and which if you implemented in your application I will have to ask you to no longer come back and ask any ASP.NET MVC related question on StackOverflow :-)
The pornographic approach consisted into manually inserting an item with id = 0 and text = empty string into the beginning of the list and then inside the controller verifying if the selected id equals 0 in order to check whether the model is valid or not:
So in your GET action:
Function Create(id As Integer) As ViewResult
ViewBag.id = id
Dim job As Job = New Job
job.CustomerId = id
job.JobAmount = 0
job.JobDate = Date.Now()
job.JobStatus = "Active"
Dim Bills = db.Bills.ToList().Select(Function(s) New SelectListItem With { .Value = s.BillId.ToString(), .Text = s.BillDate.ToString() })
Bills.Insert(0, New SelectListItem With { .Value = "0", .Text = "" })
ViewBag.BillId = Bills
Return View(job)
End Function
<HttpPost()>
Function Create(job As Job, BillId as Integer) As ActionResult
If BillId > 0 Then
db.Jobs.Add(job)
db.SaveChanges()
Dim customer As Customer = db.Customers.Find(job.CustomerId)
Dim customerNumber As String = customer.CustCellphone.ToString()
Dim messageSender As SendMessage = New SendMessage
Dim smsMessage As String = "LAUNDRY: Job Number " & job.JobId & " has been booked in. You will be notified when individual services within it are ready for collection."
messageSender.SendMessage(smsMessage, customerNumber)
Dim url As String = "/RequestedService/AddService/" + job.JobId.ToString()
Return Redirect(url)
End If
ModelState.AddModelError("BillId", "Please select a bill")
Return View(job)
End Function
and inside the view:
#Html.DropDownList("BillId")

datagridview with datasource out of bound index

I'm binding some fields to a datagridview with
myDataGridView.datasource = List(of MyCustomObject)
And i never touch the indexes manually but i'm getting -1 index have no value (so, an out of bound error)
The error comes on the onRowEnter() Event when I select any row in the grid.
It doesn't even enter any of my events for handling my clic, it bugs before...
On the interface,just before clicking,
I can see that no rows of grid 2 is the (currentRow).
I guess the bug comes from there but I don't know how to set a currentRow Manually or simply avoid this bug...
Any one have seen this before?
edit -
I've added some code to test:
dgvAssDet.CurrentCell = dgvAssDet.Rows(0).Cells(0)
When this assignation runs, the currentCell = nothing,
there is > 5 rows and columns...
And i've got the same error, before changing the old currentCell it trys to retrieve it,
but in my case there is none and it bugs... I've got no idea why.
When you use a DataSource on a DGV, you should use the collection System.ComponentModel.BindingList<T>, not System.Collections.Generic.List<T>
public class MyObject
{
public int Field1 { get; set; }
public MyObject() { }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewTest();
}
public void DataGridViewTest() {
BindingList<MyObject> objects = new BindingList<MyObject>();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = objects;
dataGridView1.AllowUserToAddRows = true;
objects.Add(new MyObject() {
Field1 = 1
});
}
}
If your objects list was the type of List<T> you would get the index out of bounds error.

Update SqlCE database Linq-to-Sql

When I update the database, I have to hard code mapping of each property, because using attach results in exception. This does not seem too elegant. Is there some easier solution here I'm not aware of? My code is below, showing the "MapData" method I call for this purpose:
Btw, entity classes (here; Users) are autogenerated with SqlMetal.
Public Class UserDataService
Public Sub Save(ByVal user As Users)
Dim ctx As New TestDB(connection)
Dim id As Integer = user.Id
If user.Id = 0 Then
Insert(user)
Else
Dim q = (From n In ctx.Users Where n.Id = id Select n).Single
q.MapData(user)
For Each o In user.Orders
o.Save()
Next
' ctx.Users.Attach(user, q) ' Does not work
' ctx.Users.Attach(user, True) ' Does not work
End If
ctx.SubmitChanges()
ctx.Dispose()
End Sub
End Class
Partial Public Class Users
Public Sub MapData(ByVal row As Users)
Me.Name = row.Name
End Sub
End Class
EDIT1:
Exceptions:
ctx.Users.Attach(user, q)
Cannot add an entity with a key that is already in use.
ctx.Users.Attach(user, True)
An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
EDIT2:
I tried to add a column timestamp, which I believe is supposed to satisfy the last mentioned exception. So I add the column shown here. This doesn't help, but perhaps I need to make some further settings for that to be effective?
This way should work:
ctx.Users.Attach(user)
ctx.Refresh(RefreshMode.KeepCurrentValues, user) 'this line is important
ctx.SubmitChanges()
This is my console test app(it works), in C# though:
class Program
{
public static void Main(string[] args)
{
var t = new Test();
Customer c = t.GetCustomer();
c.CompanyName = "X";
t.AttachCustomer(c);
}
class Test
{
public Customer GetCustomer()
{
Customer cust;
using(DataContext db = new DataContext())
{
cust = db.Customers.Where(x => x.CustomerID == "ALFKI").Single();
db.Dispose();
}
return cust;
}
public void AttachCustomer(Customer cx)
{
using (DataContext db = new DataContext())
{
db.Customers.Attach(cx);
db.Refresh(RefreshMode.KeepCurrentValues, cx);
db.SubmitChanges();
db.Dispose();
}
}
}
}

Hiding and Showing TabPages in tabControl

I am trying to show or hide tabpages as per user choice. If user selects gender male then form for male in a tabpage "male" should be displayed and if user selects female then similar next form should be displayed in next tab "female"
I tried using
tabControl1.TabPages.Remove(...)
and
tabControl1.TabPages.Add(...)
It adds and removes the tabpages but doing so will loose my controls on tabpages too... i can't see them back. what's the problem here?
I think the answer is much easier.
To hide the tab you just can use the way you already tried or adressing the TabPage itself.
TabControl1.TabPages.Remove(TabPage1) 'Could be male
TabControl1.TabPages.Remove(TabPage2) 'Could be female
a.s.o.
Removing the TabPage does not destroy it and the controls on it.
To show the corresponding tab again just use the following code
TabControl1.TabPages.Insert(0, TabPage1) 'Show male
TabControl1.TabPages.Insert(1, TabPage2) 'Show female
You could remove the tab page from the TabControl.TabPages collection and store it in a list. For example:
private List<TabPage> hiddenPages = new List<TabPage>();
private void EnablePage(TabPage page, bool enable) {
if (enable) {
tabControl1.TabPages.Add(page);
hiddenPages.Remove(page);
}
else {
tabControl1.TabPages.Remove(page);
hiddenPages.Add(page);
}
}
protected override void OnFormClosed(FormClosedEventArgs e) {
foreach (var page in hiddenPages) page.Dispose();
base.OnFormClosed(e);
}
Improving on the good solution by Hans Passant I decided to write an extension method based on his solution and adding other stuff as well. I am surprised that even in .NET 4 this basic functionality hasn't been fixed.
Implemented it as an Extension Method that can be reused in a more transparent manner
The clean up method only cleans up the pages of the control being disposed/cleaned up.
Whenever possible the tab page is restored to its same position. This isn't always
possible if you hide/show several tab pages.
It does some error and parameter checking
To make it invisible it finds out its parent. When making visible it has to be given
because the Parent property is null when the tab page has been removed.
public static class TabPageExtensions
{
private struct TabPageData
{
internal int Index;
internal TabControl Parent;
internal TabPage Page;
internal TabPageData(int index, TabControl parent, TabPage page)
{
Index = index;
Parent = parent;
Page = page;
}
internal static string GetKey(TabControl tabCtrl, TabPage tabPage)
{
string key = "";
if (tabCtrl != null && tabPage != null)
{
key = String.Format("{0}:{1}", tabCtrl.Name, tabPage.Name);
}
return key;
}
}
private static Dictionary<string, TabPageData> hiddenPages = new Dictionary<string, TabPageData>();
public static void SetVisible(this TabPage page, TabControl parent)
{
if (parent != null && !parent.IsDisposed)
{
TabPageData tpinfo;
string key = TabPageData.GetKey(parent, page);
if (hiddenPages.ContainsKey(key))
{
tpinfo = hiddenPages[key];
if (tpinfo.Index < parent.TabPages.Count)
parent.TabPages.Insert(tpinfo.Index, tpinfo.Page); // add the page in the same position it had
else
parent.TabPages.Add(tpinfo.Page);
hiddenPages.Remove(key);
}
}
}
public static void SetInvisible(this TabPage page)
{
if (IsVisible(page))
{
TabControl tabCtrl = (TabControl)page.Parent;
TabPageData tpinfo;
tpinfo = new TabPageData(tabCtrl.TabPages.IndexOf(page), tabCtrl, page);
tabCtrl.TabPages.Remove(page);
hiddenPages.Add(TabPageData.GetKey(tabCtrl, page), tpinfo);
}
}
public static bool IsVisible(this TabPage page)
{
return page != null && page.Parent != null; // when Parent is null the tab page does not belong to any container
}
public static void CleanUpHiddenPages(this TabPage page)
{
foreach (TabPageData info in hiddenPages.Values)
{
if (info.Parent != null && info.Parent.Equals((TabControl)page.Parent))
info.Page.Dispose();
}
}
}
A different approach would be to have two tab controls, one visible, and one not. You can move the tabs from one to the other like this (vb.net):
If Me.chkShowTab1.Checked = True Then
Me.tabsShown.TabPages.Add(Me.tabsHidden.TabPages("Tab1"))
Me.tabsHidden.TabPages.RemoveByKey("Tab1")
Else
Me.tabsHidden.TabPages.Add(Me.tabsShown.TabPages("Tab1"))
Me.tabsShown.TabPages.RemoveByKey("Tab1")
End If
If the tab order is important, change the .Add method on tabsShown to .Insert and specify the ordinal position. One way to do that is to call a routine that returns the desired ordinal position.
I prefer to make the flat style appearance:
https://stackoverflow.com/a/25192153/5660876
tabControl1.Appearance = TabAppearance.FlatButtons;
tabControl1.ItemSize = new Size(0, 1);
tabControl1.SizeMode = TabSizeMode.Fixed;
But there is a pixel that is shown at every tabPage, so if you delete all the text of every tabpage, then the tabs become invisible perfectly at run-time.
foreach (TabPage tab in tabControl1.TabPages)
{
tab.Text = "";
}
After that i use a treeview, to change through the tabpages... clicking on the nodes.
you can always hide or show the tabpage.
'in VB
myTabControl.TabPages(9).Hide() 'to hide the tabpage that has index 9
myTabControl.TabPages(9).Show() 'to show the tabpage that has index 9
I have my sample code working but want to make it somewhat more better refrencing the tab from list:
Public Class Form1
Dim State1 As Integer = 1
Dim AllTabs As List(Of TabPage) = New List(Of TabPage)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Check1(State1)
State1 = CInt(IIf(State1 = 1, 0, 1))
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AllTabs.Add(TabControl1.TabPages("TabPage1"))
AllTabs.Add(TabControl1.TabPages("TabPage2"))
End Sub
Sub Check1(ByVal No As Integer)
If TabControl1.TabPages.ContainsKey("TabPage1") Then
TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage1"))
End If
If TabControl1.TabPages.ContainsKey("TabPage2") Then
TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage2"))
End If
TabControl1.TabPages.Add(AllTabs(No))
End Sub
End Class
public static Action<Func<TabPage, bool>> GetTabHider(this TabControl container) {
if (container == null) throw new ArgumentNullException("container");
var orderedCache = new List<TabPage>();
var orderedEnumerator = container.TabPages.GetEnumerator();
while (orderedEnumerator.MoveNext()) {
var current = orderedEnumerator.Current as TabPage;
if (current != null) {
orderedCache.Add(current);
}
}
return (Func<TabPage, bool> where) => {
if (where == null) throw new ArgumentNullException("where");
container.TabPages.Clear();
foreach (TabPage page in orderedCache) {
if (where(page)) {
container.TabPages.Add(page);
}
}
};
}
Used like this:
var showOnly = this.TabContainer1.GetTabHider();
showOnly((tab) => tab.Text != "tabPage1");
Original ordering is retained by retaining a reference to the anonymous function instance.
It looks easier for me to clear all TabPages add add those wished:
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(AspectTabPage);
PropertyTabControl.TabPages.Add(WerkstattTabPage);
or
PropertyTabControl.TabPages.Clear();
PropertyTabControl.TabPages.Add(TerminTabPage);
Someone merged the C# answer into this one so I have to post my answer here. I didn't love the other solutions so I made a helper class that will make it easier to hide / show your tabs while retaining the order of tabs.
/// <summary>
/// Memorizes the order of tabs upon creation to make hiding / showing tabs more
/// straightforward. Instead of interacting with the TabCollection, use this class
/// instead.
/// </summary>
public class TabPageHelper
{
private List<TabPage> _allTabs;
private TabControl.TabPageCollection _tabCollection;
public Dictionary<string, int> TabOrder { get; private set; }
public TabPageHelper( TabControl.TabPageCollection tabCollection )
{
_allTabs = new List<TabPage>();
TabOrder = new Dictionary<string, int>();
foreach ( TabPage tab in tabCollection )
{
_allTabs.Add( tab );
}
_tabCollection = tabCollection;
foreach ( int index in Enumerable.Range( 0, tabCollection.Count ) )
{
var tab = tabCollection[index];
TabOrder[tab.Name] = index;
}
}
public void ShowTabPage( string tabText )
{
TabPage page = _allTabs
.Where( t => string.Equals( t.Text, tabText, StringComparison.CurrentCultureIgnoreCase ) )
.First();
int tabPageOrder = TabOrder[page.Name];
if ( !_tabCollection.Contains( page ) )
{
_tabCollection.Insert( tabPageOrder, page );
}
}
public void HideTabPage( string tabText )
{
TabPage page = _allTabs
.Where( t => string.Equals( t.Text, tabText, StringComparison.CurrentCultureIgnoreCase ) )
.First();
int tabPageOrder = TabOrder[page.Name];
if ( _tabCollection.Contains( page ) )
{
_tabCollection.Remove( page );
}
}
}
To use the class, instantiate it in your form load method after initializing your components by passing in the tab control's TabPages property.
public Form1()
{
InitializeComponent();
_tabHelper = new TabPageHelper( tabControl1.TabPages );
}
All of your tab pages should exist on application load (ie: in the Design view) because the class will remember the order of the tab pages when hiding / showing. You can hide or show them selectively throughout your application like this:
_tabHelper.HideTabPage("Settings");
_tabHelper.ShowTabPage("Schedule");
I've been using the same approach of saving the hidden TabPages in a private list, but the problem is that when I want to show the TabPage again, they doesn't appears in the original position (order). So, finally, I wrote a class in VB to add the TabControl with two methods: HideTabPageByName and ShowTabPageByName. You can just call the methods passing the name (not the TabPage instance).
Public Class CS_Control_TabControl
Inherits System.Windows.Forms.TabControl
Private mTabPagesHidden As New Dictionary(Of String, System.Windows.Forms.TabPage)
Private mTabPagesOrder As List(Of String)
Public Sub HideTabPageByName(ByVal TabPageName As String)
If mTabPagesOrder Is Nothing Then
' The first time the Hide method is called, save the original order of the TabPages
mTabPagesOrder = New List(Of String)
For Each TabPageCurrent As TabPage In Me.TabPages
mTabPagesOrder.Add(TabPageCurrent.Name)
Next
End If
If Me.TabPages.ContainsKey(TabPageName) Then
Dim TabPageToHide As TabPage
' Get the TabPage object
TabPageToHide = TabPages(TabPageName)
' Add the TabPage to the internal List
mTabPagesHidden.Add(TabPageName, TabPageToHide)
' Remove the TabPage from the TabPages collection of the TabControl
Me.TabPages.Remove(TabPageToHide)
End If
End Sub
Public Sub ShowTabPageByName(ByVal TabPageName As String)
If mTabPagesHidden.ContainsKey(TabPageName) Then
Dim TabPageToShow As TabPage
' Get the TabPage object
TabPageToShow = mTabPagesHidden(TabPageName)
' Add the TabPage to the TabPages collection of the TabControl
Me.TabPages.Insert(GetTabPageInsertionPoint(TabPageName), TabPageToShow)
' Remove the TabPage from the internal List
mTabPagesHidden.Remove(TabPageName)
End If
End Sub
Private Function GetTabPageInsertionPoint(ByVal TabPageName As String) As Integer
Dim TabPageIndex As Integer
Dim TabPageCurrent As TabPage
Dim TabNameIndex As Integer
Dim TabNameCurrent As String
For TabPageIndex = 0 To Me.TabPages.Count - 1
TabPageCurrent = Me.TabPages(TabPageIndex)
For TabNameIndex = TabPageIndex To mTabPagesOrder.Count - 1
TabNameCurrent = mTabPagesOrder(TabNameIndex)
If TabNameCurrent = TabPageCurrent.Name Then
Exit For
End If
If TabNameCurrent = TabPageName Then
Return TabPageIndex
End If
Next
Next
Return TabPageIndex
End Function
Protected Overrides Sub Finalize()
mTabPagesHidden = Nothing
mTabPagesOrder = Nothing
MyBase.Finalize()
End Sub
End Class
Public Shared HiddenTabs As New List(Of TabPage)()
Public Shared Visibletabs As New List(Of TabPage)()
Public Shared Function ShowTab(tab_ As TabPage, show_tab As Boolean)
Select Case show_tab
Case True
If Visibletabs.Contains(tab_) = False Then Visibletabs.Add(tab_)
If HiddenTabs.Contains(tab_) = True Then HiddenTabs.Remove(tab_)
Case False
If HiddenTabs.Contains(tab_) = False Then HiddenTabs.Add(tab_)
If Visibletabs.Contains(tab_) = True Then Visibletabs.Remove(tab_)
End Select
For Each r In HiddenTabs
Try
Dim TC As TabControl = r.Parent
If TC.Contains(r) = True Then TC.TabPages.Remove(r)
Catch ex As Exception
End Try
Next
For Each a In Visibletabs
Try
Dim TC As TabControl = a.Parent
If TC.Contains(a) = False Then TC.TabPages.Add(a)
Catch ex As Exception
End Try
Next
End Function
And building upon the answer by Emile (and Slugster), I found it a bit easier to extend the TabControl (instead of the TabPages). In this way I can set pages invisible or visible with a single call, and also not have to worry about the null parent references for the invisible pages.
Example call:
MyTabControl.SetTabVisibilityExt( "tabTests", isDeveloper);
public static class WinFormExtensions
{
public static TabPage FindTabByNameExt( this TabControl tc, string tabName)
{
foreach (TabPage tab in tc.TabPages)
if (tab.Name == tabName)
return tab;
return null;
}
private struct TabPageData
{
internal int Index;
internal TabControl Parent;
internal TabPage Page;
internal TabPageData(int index, TabControl parent, TabPage page)
{
Index = index;
Parent = parent;
Page = page;
}
internal static string GetKey(TabControl tc, TabPage tabPage)
{
string key = "";
if (tc == null || tabPage == null)
return key;
key = $"{tc.Name}:{tabPage.Name}";
return key;
}
internal static string GetKey(TabControl tc, string tabName)
{
string key = "";
if (tc == null)
return key;
key = $"{tc.Name}:{tabName}";
return key;
}
}
private static Dictionary<string, TabPageData> hiddenPages = new Dictionary<string, TabPageData>();
public static void SetTabVisibleExt(this TabControl tc, string tabName)
{
if (tc == null || tc.IsDisposed)
return;
if (tc.IsTabVisibleExt(tabName))
return;
string key = TabPageData.GetKey(tc, tabName);
if (hiddenPages.ContainsKey(key))
{
TabPageData tpinfo = hiddenPages[key];
if (tpinfo.Index < tc.TabPages.Count)
tc.TabPages.Insert(tpinfo.Index, tpinfo.Page); // add the page in the same position it had
else
tc.TabPages.Add(tpinfo.Page);
hiddenPages.Remove(key);
return;
}
else
throw new ApplicationException($"TabControl={tc.Name} does not have Invisible TabPage={tabName}");
}
public static void SetTabInvisibleExt(this TabControl tc, string tabName)
{
if (tc == null || tc.IsDisposed)
return;
if (IsTabInvisibleExt(tc, tabName))
return;
TabPage page = tc.FindTabByNameExt(tabName);
if (page != null)
{
string key = TabPageData.GetKey(tc, page);
TabPageData tpInfo = new TabPageData(tc.TabPages.IndexOf(page), tc, page);
tc.TabPages.Remove(page);
hiddenPages.Add(key, tpInfo);
return;
}
else // Could not find the tab, and it isn't already invisible.
throw new ApplicationException($"TabControl={tc.Name} could not locate TabPage={tabName}");
}
// A convenience method to combine the SetTabInvisible and SetTabInvisible.
public static void SetTabVisibilityExt(this TabControl tc, string tabName, bool? isVisible)
{
if (isVisible == null)
return;
if (isVisible.Value)
tc.SetTabVisibleExt(tabName);
else
tc.SetTabInvisibleExt(tabName);
}
public static bool IsTabVisibleExt(this TabControl tc, string tabName)
{
TabPage page = tc.FindTabByNameExt(tabName);
return page != null;
}
public static bool IsTabInvisibleExt(this TabControl tc, string tabName)
{
string key = TabPageData.GetKey(tc, tabName);
return hiddenPages.ContainsKey(key);
}
public static void CleanUpHiddenPagesExt(this TabControl tc)
{
foreach (TabPageData info in hiddenPages.Values)
{
if (info.Parent != null && info.Parent.Equals((TabControl)tc))
info.Page.Dispose();
}
}
}
If you can afford to use the Tag element of the TabPage, you can use this extension methods
public static void HideByRemoval(this TabPage tp)
{
TabControl tc = tp.Parent as TabControl;
if (tc != null && tc.TabPages.Contains(tp))
{
// Store TabControl and Index
tp.Tag = new Tuple<TabControl, Int32>(tc, tc.TabPages.IndexOf(tp));
tc.TabPages.Remove(tp);
}
}
public static void ShowByInsertion(this TabPage tp)
{
Tuple<TabControl, Int32> tagObj = tp.Tag as Tuple<TabControl, Int32>;
if (tagObj?.Item1 != null)
{
// Restore TabControl and Index
tagObj.Item1.TabPages.Insert(tagObj.Item2, tp);
}
}
Adding and removing tab may be a bit less effective
May be this will help
To hide/show tab page => let tabPage1 of tabControl1
tapPage1.Parent = null; //to hide tabPage1 from tabControl1
tabPage1.Parent = tabControl1; //to show the tabPage1 in tabControl1
There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.
Private tabControl1tabPageShadow() As TabPage = Nothing
Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadTabPageShadow()
End Sub
Private Sub LoadTabPageShadow()
ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
For Each tabPage In TabControl1.TabPages
tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
Next
End Sub
Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
TabControl1.TabPages.Clear()
For Each tabPage In tabControl1tabPageShadow
TabControl1.TabPages.Add(tabPage)
Next
End Sub
Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
TabControl1.TabPages.Clear()
For tabCount As Integer = 0 To 9
For Each tabPage In tabControl1tabPageShadow
Select Case tabPage.Text
Case "Overview"
If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
Case "Production Days Under 110%"
If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
Case "Screening Status"
If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
Case "Rework Status"
If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
Case "Secondary by Machine"
If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
Case "Secondary Set Ups"
If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
Case "Secondary Run Times"
If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
Case "Primary Set Ups"
If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
Case "Variance"
If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
Case "Schedule Changes"
If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
End Select
Next
Next
Solutions provided by Antony and Suroj are the simplest one.
In Antony's solution, that if condition is must before adding the tabpage. Adding the same tabpage again will actually add the second tabpage and remove controls on both the tabpages.
I used following code in my app.
'Hide all the tabpages except Navigator during app startup.
For Each itemTab As TabPage In TabControl1.TabPages
If itemTab.Text <> "Navigator" Then
TabControl1.TabPages.Remove(itemTab)
End If
Next
'Show the tab on button click
If Not TabControl1.Controls.Contains(TabDataSource) Then
TabControl1.TabPages.Add(TabDataSource)
End If
TabControl1.SelectedTab = TabDataSource
Always codes should be simple and easy to perform tasks for fast performance and for good reliability.
To add a page to a TabControl, the following code is enough.
If Tabcontrol1.Controls.Contains(TabPage1) Then
else
Tabcontrol1.Controls.Add(TabPage1)
End If
To remove a page from a TabControl, the following code is enough.
If Tabcontrol1.Controls.Contains(TabPage1) Then
Tabcontrol1.Controls.Remove(TabPage1)
End If
I wish to thank Stackoverflow.com for providing sincere help to programmers.
TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1
First copy the tab into a variable then use insert to bring it back.
TabPage tpresult = tabControl1.TabPages[0];
tabControl1.TabPages.RemoveAt(0);
tabControl1.TabPages.Insert(0, tpresult);
You Can Use the Following
tabcontainer.tabs(1).visible=true
1 is tabindex