Hiding and Showing TabPages in tabControl - vb.net

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

Related

Adding quantity if the product is exist in the DataGridView

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}";
}
}

How to make a form's area not clickable without disabling its controls

I have a Winform project in VB.net 2013.
On a form I have a lot's of controls.
When a condition is true , I need to make all the controls inside a specific form's area , not clickable ( but without disabling them )
Of course , when the condition became false the area should return to normal state.
Thank you !
You could assign a NativeWindow to each control and intercept the HITTEST message.
E.g. This example only does it for the immediate Form's children. You could also recurse through all the children.
Form f = new Form();
f.Controls.Add(new Button { Text = "test test test "});
Form f2 = new Form();
CheckBox cb = new CheckBox { Text = "Toggle" };
f2.Controls.Add(cb);
List<NW> nws = null;
cb.CheckedChanged += delegate {
if (nws == null) {
nws = new List<NW>();
foreach (Control c in f.Controls) {
nws.Add(new NW(c.Handle));
}
}
else {
foreach (var nw in nws)
nw.ReleaseHandle();
nws = null;
}
};
f.Show();
Application.Run(f2);
class NW : NativeWindow {
public NW(IntPtr hwnd) {
AssignHandle(hwnd);
}
const int WM_NCHITTEST = 0x84;
protected override void WndProc(ref Message m) {
if (m.Msg == WM_NCHITTEST)
return;
base.WndProc(ref m);
}
}
Place all controls in a PANEL and then disable that panel.
panel.Enabled= false;

Add spell check functionality to windows form textbox [duplicate]

I am trying to use the SpellCheck class C# provides (in PresentationFramework.dll).
But, I am experiencing problems when trying to bind the spelling to my textbox:
SpellCheck.SetIsEnabled(txtWhatever, true);
The problem is that my txtWhatever is of type System.Windows.Forms and the parameter this function is looking for is System.Windows.Controls, and simple converting failed.
I also tried to make my TextBox of this type, but... couldn't.
Does anyone know how to use this SpellCheck object?
(MSDN wasn't that helpful...)
Thanks
You have to use a WPF TextBox to make spell checking work. You can embed one in a Windows Forms form with the ElementHost control. It works pretty similar to a UserControl. Here's a control that you can drop straight from the toolbox. To get started, you need Project + Add Reference and select WindowsFormsIntegration, System.Design and the WPF assemblies PresentationCore, PresentationFramework and WindowsBase.
Add a new class to your project and paste the code shown below. Compile. Drop the SpellBox control from the top of the toolbox onto a form. It supports the TextChanged event and the Multiline and WordWrap properties. There's a nagging problem with the Font, there is no easy way to map a WF Font to the WPF font properties. The easiest workaround for that is to set the form's Font to "Segoe UI", the default for WPF.
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Forms.Design;
[Designer(typeof(ControlDesigner))]
//[DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
class SpellBox : ElementHost {
public SpellBox() {
box = new TextBox();
base.Child = box;
box.TextChanged += (s, e) => OnTextChanged(EventArgs.Empty);
box.SpellCheck.IsEnabled = true;
box.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
this.Size = new System.Drawing.Size(100, 20);
}
public override string Text {
get { return box.Text; }
set { box.Text = value; }
}
[DefaultValue(false)]
public bool Multiline {
get { return box.AcceptsReturn; }
set { box.AcceptsReturn = value; }
}
[DefaultValue(false)]
public bool WordWrap {
get { return box.TextWrapping != TextWrapping.NoWrap; }
set { box.TextWrapping = value ? TextWrapping.Wrap : TextWrapping.NoWrap; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new System.Windows.UIElement Child {
get { return base.Child; }
set { /* Do nothing to solve a problem with the serializer !! */ }
}
private TextBox box;
}
By popular demand, a VB.NET version of this code that avoids the lambda:
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Design.Serialization
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Forms.Integration
Imports System.Windows.Forms.Design
<Designer(GetType(ControlDesigner))> _
Class SpellBox
Inherits ElementHost
Public Sub New()
box = New TextBox()
MyBase.Child = box
AddHandler box.TextChanged, AddressOf box_TextChanged
box.SpellCheck.IsEnabled = True
box.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
Me.Size = New System.Drawing.Size(100, 20)
End Sub
Private Sub box_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
OnTextChanged(EventArgs.Empty)
End Sub
Public Overrides Property Text() As String
Get
Return box.Text
End Get
Set(ByVal value As String)
box.Text = value
End Set
End Property
<DefaultValue(False)> _
Public Property MultiLine() As Boolean
Get
Return box.AcceptsReturn
End Get
Set(ByVal value As Boolean)
box.AcceptsReturn = value
End Set
End Property
<DefaultValue(False)> _
Public Property WordWrap() As Boolean
Get
Return box.TextWrapping <> TextWrapping.NoWrap
End Get
Set(ByVal value As Boolean)
If value Then
box.TextWrapping = TextWrapping.Wrap
Else
box.TextWrapping = TextWrapping.NoWrap
End If
End Set
End Property
<DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
Public Shadows Property Child() As System.Windows.UIElement
Get
Return MyBase.Child
End Get
Set(ByVal value As System.Windows.UIElement)
'' Do nothing to solve a problem with the serializer !!
End Set
End Property
Private box As TextBox
End Class
Have you tried just setting the property on the actual TextBox your attempting to spellcheck. e.g.
txtWhatever.SpellCheck.IsEnabled = true;
You're trying to use a spell-check component designed for WPF on a WinForms application. They're incompatible.
If you want to use the .NET-provided spell check, you'll have to use WPF as your widget system.
If you want to stick with WinForms, you'll need a third-party spell check component.
Free .NET spell checker based around a WPF text box that can be used client or server side can be seen here. It will wrap the text box for you although you still need the assembly includes to Presentation framework etc.
Full disclosure...written by yours truly
I needed to add a background colour to the textbox in winforms that reflected the colour selected in the designer:
public override System.Drawing.Color BackColor
{
get
{
if (box == null) { return Color.White; }
System.Windows.Media.Brush br = box.Background;
byte a = ((System.Windows.Media.SolidColorBrush)(br)).Color.A;
byte g = ((System.Windows.Media.SolidColorBrush)(br)).Color.G;
byte r = ((System.Windows.Media.SolidColorBrush)(br)).Color.R;
byte b = ((System.Windows.Media.SolidColorBrush)(br)).Color.B;
return System.Drawing.Color.FromArgb((int)a, (int)r, (int)g, (int)b);
}
set
{
box.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(value.A, value.R, value.G, value.B));
}
}
If you want to enable the TextChanged Event write the code like this.
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Forms.Design;
[Designer(typeof(ControlDesigner))]
//[DesignerSerializer("System.Windows.Forms.Design.ControlCodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.ComponentModel.Design.Serialization.CodeDomSerializer, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
class SpellBox : ElementHost
{
public SpellBox()
{
box = new TextBox();
base.Child = box;
box.TextChanged += (s, e) => OnTextChanged(EventArgs.Empty);
box.SpellCheck.IsEnabled = true;
box.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
box.TextChanged += new System.Windows.Controls.TextChangedEventHandler(SpellBox_TextChanged);
this.Size = new System.Drawing.Size(100, 20);
}
[Browsable(true)]
[Category("Action")]
[Description("Invoked when Text Changes")]
public new event EventHandler TextChanged;
protected void SpellBox_TextChanged(object sender, EventArgs e)
{
if (this.TextChanged!=null)
this.TextChanged(this, e);
}
public override string Text
{
get { return box.Text; }
set { box.Text = value; }
}
[DefaultValue(false)]
public bool Multiline
{
get { return box.AcceptsReturn; }
set { box.AcceptsReturn = value; }
}
[DefaultValue(false)]
public bool WordWrap
{
get { return box.TextWrapping != TextWrapping.NoWrap; }
set { box.TextWrapping = value ? TextWrapping.Wrap : TextWrapping.NoWrap; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new System.Windows.UIElement Child
{
get { return base.Child; }
set { /* Do nothing to solve a problem with the serializer !! */ }
}
private TextBox box;
}
what about getting a list of words in the english language and copying that to a text file. add the reference. then use streamreader class to analyze the list against textbox.text. any words not found in the text file could be set to be highlighted or displayed in a dialog box with options to replace or ignore. this is a shotgun suggestion with many missing steps and i am 2 months into programming but....its what im going to attempt anyway. i am making a notepad project (rexpad on idreamincode.com). hope this helped!

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.

How to make a custom ComboBox (OwnerDrawFixed) looks 3D like the standard ComboBox?

I am making a custom ComboBox, inherited from Winforms' standard ComboBox. For my custom ComboBox, I set DrawMode to OwnerDrawFixed and DropDownStyle to DropDownList. Then I write my own OnDrawItem method. But I ended up like this:
How do I make my Custom ComboBox to look like the Standard one?
Update 1: ButtonRenderer
After searching all around, I found the ButtonRenderer class. It provides a DrawButton static/shared method which -- as the name implies -- draws the proper 3D button. I'm experimenting with it now.
Update 2: What overwrites my control?
I tried using the Graphics properties of various objects I can think of, but I always fail. Finally, I tried the Graphics of the form, and apparently something is overwriting my button.
Here's the code:
Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
Dim TextToDraw As String = _DefaultText
__Brush_Window.Color = Color.FromKnownColor(KnownColor.Window)
__Brush_Disabled.Color = Color.FromKnownColor(KnownColor.GrayText)
__Brush_Enabled.Color = Color.FromKnownColor(KnownColor.WindowText)
If e.Index >= 0 Then
TextToDraw = _DataSource.ItemText(e.Index)
End If
If TextToDraw.StartsWith("---") Then TextToDraw = StrDup(3, ChrW(&H2500)) ' U+2500 is "Box Drawing Light Horizontal"
If (e.State And DrawItemState.ComboBoxEdit) > 0 Then
'ButtonRenderer.DrawButton(e.Graphics, e.Bounds, VisualStyles.PushButtonState.Default)
Else
e.DrawBackground()
End If
With e
If _IsEnabled(.Index) Then
.Graphics.DrawString(TextToDraw, Me.Font, __Brush_Enabled, .Bounds.X, .Bounds.Y)
Else
'.Graphics.FillRectangle(__Brush_Window, .Bounds)
.Graphics.DrawString(TextToDraw, Me.Font, __Brush_Disabled, .Bounds.X, .Bounds.Y)
End If
End With
TextToDraw = Nothing
ButtonRenderer.DrawButton(Me.Parent.CreateGraphics, Me.ClientRectangle, VisualStyles.PushButtonState.Default)
'MyBase.OnDrawItem(e)
End Sub
And here's the result:
Replacing Me.Parent.CreateGraphics with e.Graphics got me this:
And doing the above + replacing Me.ClientRectangle with e.Bounds got me this:
Can anyone point me whose Graphics I must use for the ButtonRenderer.DrawButton method?
PS: The bluish border is due to my using PushButtonState.Default instead of PushButtonState.Normal
I Found An Answer! (see below)
I forgot where I found the answer... I'll edit this answer when I remember.
But apparently, I need to set the Systems.Windows.Forms.ControlStyles flags. Especially the ControlStyles.UserPaint flag.
So, my New() now looks like this:
Private _ButtonArea as New Rectangle
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
MyBase.SetStyle(ControlStyles.Opaque Or ControlStyles.UserPaint, True)
MyBase.DrawMode = Windows.Forms.DrawMode.OwnerDrawFixed
MyBase.DropDownStyle = ComboBoxStyle.DropDownList
' Cache the button's modified ClientRectangle (see Note)
With _ButtonArea
.X = Me.ClientRectangle.X - 1
.Y = Me.ClientRectangle.Y - 1
.Width = Me.ClientRectangle.Width + 2
.Height = Me.ClientRectangle.Height + 2
End With
End Sub
And now I can hook into the OnPaint event:
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
If Me.DroppedDown Then
ButtonRenderer.DrawButton(Me.CreateGraphics, _ButtonArea, VisualStyles.PushButtonState.Pressed)
Else
ButtonRenderer.DrawButton(Me.CreateGraphics, _ButtonArea, VisualStyles.PushButtonState.Normal)
End If
MyBase.OnPaint(e)
End Sub
Note: Yes, the _ButtonArea rectangle must be enlarged by 1 pixel to all directions (up, down, left, right), or else there will be a 1-pixel 'perimeter' around the ButtonRenderer that shows garbage. Made me crazy for awhile until I read that I must enlarge the Control's rect for ButtonRenderer.
I had this problem myself and the reply by pepoluan got me started. I still think a few things are missing in order to get a ComboBox with looks and behavior similar to the standard ComboBox with DropDownStyle=DropDownList though.
DropDownArrow
We also need to draw the DropDownArrow. I played around with the ComboBoxRenderer, but it draws a dark border around the area of the drop down arrow so that didn't work.
My final solution was to simply draw a similar arrow and render it onto the button in the OnPaint method.
Hot Item Behavior
We also need to ensure our ComboBox has a hot item behavior similar to the standard ComboBox. I don't know of any simple and reliable method to know when a mouse is no longer above the control. Therefore I suggest using a Timer that checks at each tick whether the mouse is still over the control.
Edit
Just added a KeyUp event handler to make sure the control would update correctly when a selection was made using the keyboard. Also made a minor correction of where the text was rendered, to ensure it is more similar to the vanilla combobox' text positioning.
Below is the full code of my customized ComboBox. It allows you to display images on each item and is always rendered as in the DropDownList style, but hopefully it should be easy to accommodate the code to your own solution.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace CustomControls
{
/// <summary>
/// This is a special ComboBox that each item may conatins an image.
/// </summary>
public class ImageComboBox : ComboBox
{
private static readonly Size arrowSize = new Size(18, 20);
private bool itemIsHot;
/* Since properties such as SelectedIndex and SelectedItems may change when the mouser is hovering over items in the drop down list
* we need a property that will store the item that has been selected by comitted selection so we know what to draw as the selected item.*/
private object comittedSelection;
private readonly ImgHolder dropDownArrow = ImgHolder.Create(ImageComboBox.DropDownArrow());
private Timer hotItemTimer;
public Font SelectedItemFont { get; set; }
public Padding ImageMargin { get; set; }
//
// Summary:
// Gets or sets the path of the property to use as the image for the items
// in the System.Windows.Forms.ListControl.
//
// Returns:
// A System.String representing a single property name of the System.Windows.Forms.ListControl.DataSource
// property value, or a hierarchy of period-delimited property names that resolves
// to a property name of the final data-bound object. The default is an empty string
// ("").
//
// Exceptions:
// T:System.ArgumentException:
// The specified property path cannot be resolved through the object specified by
// the System.Windows.Forms.ListControl.DataSource property.
[DefaultValue("")]
[Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string ImageMember { get; set; }
public ImageComboBox()
{
base.SetStyle(ControlStyles.Opaque | ControlStyles.UserPaint, true);
//All the elements in the control are drawn manually.
base.DrawMode = DrawMode.OwnerDrawFixed;
//Specifies that the list is displayed by clicking the down arrow and that the text portion is not editable.
//This means that the user cannot enter a new value.
//Only values already in the list can be selected.
this.DropDownStyle = ComboBoxStyle.DropDownList;
//using DrawItem event we need to draw item
this.DrawItem += this.ComboBoxDrawItemEvent;
this.hotItemTimer = new Timer();
this.hotItemTimer.Interval = 250;
this.hotItemTimer.Tick += this.HotItemTimer_Tick;
this.MouseEnter += this.ImageComboBox_MouseEnter;
this.KeyUp += this.ImageComboBox_KeyUp;
this.SelectedItemFont = this.Font;
this.ImageMargin = new Padding(4, 4, 5, 4);
this.SelectionChangeCommitted += this.ImageComboBox_SelectionChangeCommitted;
this.SelectedIndexChanged += this.ImageComboBox_SelectedIndexChanged;
}
private static Image DropDownArrow()
{
var arrow = new Bitmap(8, 4, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(arrow))
{
g.CompositingQuality = CompositingQuality.HighQuality;
g.FillPolygon(Brushes.Black, ImageComboBox.CreateArrowHeadPoints());
}
return arrow;
}
private static PointF[] CreateArrowHeadPoints()
{
return new PointF[4] { new PointF(0, 0), new PointF(7F, 0), new PointF(3.5F, 3.5F), new PointF(0, 0) };
}
private static void DrawComboBoxItem(Graphics g, string text, Image image, Rectangle itemArea, int itemHeight, int itemWidth, Padding imageMargin
, Brush brush, Font font)
{
if (image != null)
{
// recalculate margins so image is always approximately vertically centered
int extraImageMargin = itemHeight - image.Height;
int imageMarginTop = Math.Max(imageMargin.Top, extraImageMargin / 2);
int imageMarginBotttom = Math.Max(imageMargin.Bottom, extraImageMargin / 2);
g.DrawImage(image, itemArea.X + imageMargin.Left, itemArea.Y + imageMarginTop, itemHeight, itemHeight - (imageMarginBotttom
+ imageMarginTop));
}
const double TEXT_MARGIN_TOP_PROPORTION = 1.1;
const double TEXT_MARGIN_BOTTOM_PROPORTION = 2 - TEXT_MARGIN_TOP_PROPORTION;
int textMarginTop = (int)Math.Round((TEXT_MARGIN_TOP_PROPORTION * itemHeight - g.MeasureString(text, font).Height) / 2.0, 0);
int textMarginBottom = (int)Math.Round((TEXT_MARGIN_BOTTOM_PROPORTION * itemHeight - g.MeasureString(text, font).Height) / 2.0, 0);
//we need to draw the item as string because we made drawmode to ownervariable
g.DrawString(text, font, brush, new RectangleF(itemArea.X + itemHeight + imageMargin.Left + imageMargin.Right, itemArea.Y + textMarginTop
, itemWidth, itemHeight - textMarginBottom));
}
private string GetDistplayText(object item)
{
if (this.DisplayMember == string.Empty) { return item.ToString(); }
else
{
var display = item.GetType().GetProperty(this.DisplayMember).GetValue(item).ToString();
return display ?? item.ToString();
}
}
private Image GetImage(object item)
{
if (this.ImageMember == string.Empty) { return null; }
else { return item.GetType().GetProperty(this.ImageMember).GetValue(item) as Image; }
}
private void ImageComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
this.comittedSelection = this.Items[this.SelectedIndex];
}
private void HotItemTimer_Tick(object sender, EventArgs e)
{
if (!this.RectangleToScreen(this.ClientRectangle).Contains(Cursor.Position)) { this.TurnOffHotItem(); }
}
private void ImageComboBox_KeyUp(object sender, KeyEventArgs e)
{
this.Invalidate();
}
private void ImageComboBox_MouseEnter(object sender, EventArgs e)
{
this.TurnOnHotItem();
}
private void ImageComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DroppedDown)
{
if (this.SelectedIndex > -1) { this.comittedSelection = this.Items[this.SelectedIndex]; }
else { this.comittedSelection = null; }
}
}
private void TurnOnHotItem()
{
this.itemIsHot = true;
this.hotItemTimer.Enabled = true;
}
private void TurnOffHotItem()
{
this.itemIsHot = false;
this.hotItemTimer.Enabled = false;
this.Invalidate(this.ClientRectangle);
}
/// <summary>
/// Draws overridden items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxDrawItemEvent(object sender, DrawItemEventArgs e)
{
//Draw backgroud of the item
e.DrawBackground();
if (e.Index != -1)
{
Brush brush;
if (e.State.HasFlag(DrawItemState.Focus) || e.State.HasFlag(DrawItemState.Selected)) { brush = Brushes.White; }
else { brush = Brushes.Black; }
object item = this.Items[e.Index];
ImageComboBox.DrawComboBoxItem(e.Graphics, this.GetDistplayText(item), this.GetImage(item), e.Bounds, this.ItemHeight, this.DropDownWidth
, new Padding(0, 1, 5, 1), brush, this.Font);
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// define the area of the control where we will write the text
var topTextRectangle = new Rectangle(e.ClipRectangle.X - 1, e.ClipRectangle.Y - 1, e.ClipRectangle.Width + 2, e.ClipRectangle.Height + 2);
using (var controlImage = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height, PixelFormat.Format32bppArgb))
{
using (Graphics ctrlG = Graphics.FromImage(controlImage))
{
/* Render the control. We use ButtonRenderer and not ComboBoxRenderer because we want the control to appear with the DropDownList style. */
if (this.DroppedDown) { ButtonRenderer.DrawButton(ctrlG, topTextRectangle, PushButtonState.Pressed); }
else if (this.itemIsHot) { ButtonRenderer.DrawButton(ctrlG, topTextRectangle, PushButtonState.Hot); }
else { ButtonRenderer.DrawButton(ctrlG, topTextRectangle, PushButtonState.Normal); }
// Draw item, if any has been selected
if (this.comittedSelection != null)
{
ImageComboBox.DrawComboBoxItem(ctrlG, this.GetDistplayText(this.comittedSelection), this.GetImage(this.comittedSelection)
, topTextRectangle, this.Height, this.Width - ImageComboBox.arrowSize.Width, this.ImageMargin, Brushes.Black, this.SelectedItemFont);
}
/* Now we need to draw the arrow. If we use ComboBoxRenderer for this job, it will display a distinct border around the dropDownArrow and we don't want that. As an alternative we define the area where the arrow should be drawn, and then procede to draw it. */
var dropDownButtonArea = new RectangleF(topTextRectangle.X + topTextRectangle.Width - (ImageComboBox.arrowSize.Width
+ this.dropDownArrow.Image.Width) / 2.0F, topTextRectangle.Y + topTextRectangle.Height - (topTextRectangle.Height
+ this.dropDownArrow.Image.Height) / 2.0F, this.dropDownArrow.Image.Width, this.dropDownArrow.Image.Height);
ctrlG.DrawImage(this.dropDownArrow.Image, dropDownButtonArea);
}
if (this.Enabled) { e.Graphics.DrawImage(controlImage, 0, 0); }
else { ControlPaint.DrawImageDisabled(e.Graphics, controlImage, 0, 0, Color.Transparent); }
}
}
}
internal struct ImgHolder
{
internal Image Image
{
get
{
return this._image ?? new Bitmap(1, 1); ;
}
}
private Image _image;
internal ImgHolder(Bitmap data)
{
_image = data;
}
internal ImgHolder(Image data)
{
_image = data;
}
internal static ImgHolder Create(Image data)
{
return new ImgHolder(data);
}
internal static ImgHolder Create(Bitmap data)
{
return new ImgHolder(data);
}
}
}