Posts

Showing posts with the label Windows Forms

Donate

How To Wrap Text In A DataGridViewColumn

Image
Given that you have data such as comments/notes/description/address that would comprise at least hundreds of characters and you want to show them on the DataGridView control, you will notice that the text is concatenated and replaced with ellipses. In order to achieve wrapping of text in a DataGridView cell, I achieved it using these steps. 1. Change the WrapMode value to True of a DataGridViewTextBoxColumn's DefaultCellStyle. 2. In my DataBindingComplete event of the DataGridView, set the AutoSizeRowsMode of the DataGridView to AllCells. C# Code private void dgvFormat_DataBindingComplete( object sender, DataGridViewBindingCompleteEventArgs e) { dgvFormat.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; } That's it.. :-)

DataGridview Check For Duplicate Values And Group Code In Separate Column

Image
Hi, I've always been a desktop developer ever since Visual Basic 6.0 came into existence. While I'm busy doing projects for the web platform, I always go back to my roots of solving desktop issues in .NET. :-D Well, going back to the issue, a certain member in Visual Basic forums posted an issue on how to check duplicate values in a particular datagridview column with DateTime as type. Once a duplicate value has been detected, the code number will be grouped in another datagridview column with label total. See sample screenshot for the desired output: After creating the logic, I proceed to converting it to code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 private void SpotDuplicates() { int i = 0; int j = 0; for (i = 0; i <= dgvDates.RowCount - 1; i++) { for (j = 0; j <= dgvDates.RowCount - 1; j++) { if (i > j) { if (Convert.ToDateTime(dgvDates[0

Find Checked Treenode In TreeView Control Using LINQ In VB.NET

Here's one way of searching through a treenode using LINQ. Assuming that the search criteria is a List or array object. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Public Class Form1 Public Shared mat As List( Of String ) = Nothing Private Sub Form1_Load (sender As System.Object, e As System.EventArgs) Handles MyBase .Load mat = New List( Of String ) mat.Add( "Books" ) mat.Add( "VB" ) mat.Add( "Drinks" ) mat.Add( "Food" ) mat.Add( "Tea" ) mat.Add( "Chod" ) End Sub Private Sub Button1_Click (sender As System.Object, e As System.EventArgs) Handles Button1.Click If Not (mat Is Nothing ) Then For Each tn As String In mat If (tvMat.Nodes.Find(tn, True ).FirstOrDefault() IsNot Nothing ) Then If (tvMat.Nodes

WIndows Forms Linear Gradients In C#.NET 2D

Image
Hi, Here's a simple demo using Linear gradients (Color Manipulation) in C#.NET Windows Forms. private int _rColor = 100; public int GenerateRGB( int cc) { int rt = 0; if (cc <= 255) { rt = Information.RGB(255, cc, 0); } else if (cc < 511) { rt = Information.RGB(255 - (cc - 255), 255, 0); } else if (cc < 766) { rt = Information.RGB(0, 255, cc - 511); } else if (cc < 1022) { rt = Information.RGB(0, 255 - (cc - 767), 255); } else if (cc < 1277) { rt = Information.RGB(0, 0, 255 - (cc - 1022)); } else { rt = Information.RGB(0, 0, 0); } return rt; } private void timer1_Tick( object sender, EventArgs e) { this .Refresh(); _rColor += 1; if (_rColor > 1500) { _rColor = 0; } } private void Form1_Paint( object sender, PaintEventArgs e) { Color color = new Color(); Random m_Rnd = new Random(); color = Color.FromArgb(255, m_Rnd.Next(0, 255), m_Rnd.Next(0, 255), m_Rnd.Next(0, 255)); using (LinearGradi

Apply ComboBox Border Color In VB.NET Windows Forms

Image
Here's a simple way to decorate border color in Combobox control. The solution is a conversion of C# code originally developed by a C# Corner forum member. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Public Sub New() ' This call is required by the designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. AddHandler Me .Paint, AddressOf DrawBorder End Sub Private Sub DrawBorder( ByVal sender As Object , ByVal e As PaintEventArgs) Dim rect As New Rectangle( Me .ComboBox1.Location.X - 1, Me .ComboBox1.Location.Y - 1, Me .ComboBox1.Width + 1, Me .ComboBox1.Height + 1) Dim pen As New Pen(Color.Red, 1) Dim g As Graphics = e.Graphics g.DrawRectangle(pen, rect) End Sub Customized Combobox

Get Check Status Of A CheckedListBox Item Using Text Instead Of Index

There was a question raised on visual basic forums if you can access an item through it's name rather than index to get it's checked status. My suggestion was to implement a custom control. However, one of the resident MVP in that forum has a better solution using extension method which is simple yet elegant. Below are the extension methods in VB.NET and C#. VB.NET Module CheckedListBoxExtensions <Extension()> Function GetItemChecked( ByVal source As CheckedListBox, ByVal text As String ) As Boolean Dim item = source.Items.Cast( Of Object )().FirstOrDefault(Function(o) source.GetItemText(o) = text) Dim index = source.Items.IndexOf(item) Return source.GetItemChecked(index) End Function End Module C#.NET public static class CheckedListBoxExtensions { public static bool GetItemChecked( this CheckedListBox source, string text) { var item = source.Items.Cast< object >()

Custom Richtextbox Control With Watermark Support In C#

There was a solution in MSDN Forums on how to add watermark to a Textbox control. I tried replacing the base class if this will work on a RichTextbox control. After testing, the custom control works as expected. /// <summary> /// Set Watermark in RichTextbox. /// </summary> public class WatermarkRichTextbox : RichTextBox { private string watermark; private Color watermarkColor; private Color foreColor; private bool empty; [Browsable (true)] public Color WatermarkColor { get { return watermarkColor; } set { watermarkColor = value ; if (empty) { base .ForeColor = watermarkColor; } } } [Browsable(true)] public string Watermark { get {

Creating And Consuming Custom Control Events In Windows Forms C#

In my autocomplete textbox control, I have a listbox that shows the suggested items based on user input. However, as a requirement I want to create an event that will trigger once a selection has been done in the listbox and this event will be consumed in the calling program (Main Form). To do that, you must define a custom event. After googling for a while, here are the references that made me accomplish the task: Creating Custom Events in C# Quick and Easy Custom Events Cheers!

Windows Forms Fire TextBox Control Events Defined In A User Cntrol From Main Form

In a scenario where in I have created a user control which has a textbox control with private keypress event. I drag and drop the user control to my main form and then I want to fire the keypress event defined in the user control. Assuming in my main form I have this code: private void customTextBox1_KeyPress_1( object sender, KeyPressEventArgs e) { //accept letters,numbers, spacebar and backspace key if ( char .IsLetterOrDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == ( char )Keys.Space) { e.Handled = false ; } else { e.Handled = true ; } } Note: customTextBox1 is the user control name and customTextBox1_KeyPress_1 is the user control keypress event. In order to trigger the keypress event of the textbox defined in the user control, call Keypress user control in the textbox keypress event handler. See code below: private void textBox1_KeyPress( object sende

Custom CheckedListBox DataGridView Column

Image
Here's a working custom control class on how to embed CheckedListBox as a datagridview column. Source: Need a DataGridView Custom Column of Type ListView or CheckedListBox However, this class lacked functionalities such as obtaining the checked items and preserving the checked items during painting of the datagridview cell. Here's the custom class: public class CheckedListBoxColumn : DataGridViewColumn { public CheckedListBoxColumn() : base ( new CheckedListBoxCell()) { } public override DataGridViewCell CellTemplate { get { return base .CellTemplate; } set { if ( value != null && ! value .GetType().IsAssignableFrom( typeof (CheckedListBoxCell))) { throw new InvalidCastException( "Must be a Checke

DataGridview Current Row Returns Null In SelectionChanged Event

When retrieving selected row cell values in the DataGridview, you might encounter object not set to reference of an instance. It's because the current row has not been initialized. Check first the cell value of the current row if it has cell contents. private void dgvAccounts_SelectionChanged( object sender, EventArgs e) { string countryName = string .Empty; if (dgvAccounts.SelectedRows.Count > 0) { if (dgvAccounts.CurrentRow.Cells[1].Value != null ) { countryName = dgvAccounts.CurrentRow.Cells[1].Value.ToString(); } } } This will ensure that databinding has finished. Cheers!

DataGridview Paging Using BindingSource And BindingNavigator In C#

Image
Hello, VB.NET Version Here: DataGridview Paging Using BindingSource And BindingNavigator In VB.NET Here's a simple way to integrate paging in Datagridview using BindingNavigator and BindingSource. The original source can be found here: How can we do paging in datagridview in winform . I made some modifications to simulate loading of thousands of records from a database. Main Form Class: public partial class FBinding : Form { public static int totalRecords { get ; set ; } public const int pageSize = 10; private List< string > sourceData = new List< string >(); private DataTable dtSource = new DataTable(); public FBinding() { InitializeComponent(); bindingNav.BindingSource = bindingWebsite; bindingWebsite.CurrentChanged += new EventHandler(bindingWebsite_CurrentChanged); SetSource(); bindingWebsite.DataSource = new PageOffsetList(); } void bindingWebsite_CurrentChanged( object sender, EventAr

Textbox Custom Controls With Autosuggest Features In C# Windows Forms

Image
A textbox custom control developed by Aland Li, MSDN Moderator was the basis for the creation of three new versions of textbox custom controls with Autosuggest features. I managed to fixed some bugs and improve the functionalities of the control. The first control integrates Suggest + Append feature. The second control integrates exact keyword searching which is a limitation to the built-in .NET textbox autosuggest feature that is using startswith algorithm. The third control is an enhancement of the second control with keyword highlighting. Thanks to the original creator of the control Cheers.

Measure Width Of A Given String In Pixel Using C# And Windows Forms

Here's a function to compute the text width of a given string in pixel. Original Author: Mongus Pong (Stack Overflow) protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font, float width, float height ) { if ( text == "" ) return 0 ; StringFormat format = new StringFormat ( StringFormat.GenericDefault ); RectangleF rect = new RectangleF ( 0 , 0 , width, 1000 ); CharacterRange[] ranges = { new CharacterRange ( 0 , text.Length ) }; Region[] regions = new Region[ 1 ]; format.SetMeasurableCharacterRanges ( ranges ); format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces; regions = graphics.MeasureCharacterRanges ( text, font, rect, format ); rect = regions[ 0 ].GetBounds ( graphics ); return ( int )( rect.Right ); } Greg

Close ToolStripDropdown Object When Parent Container Or Form Is Clicked In C# Windows Forms

To close the ToolStripDropdown object which is part of the textbox custom control, add event handler signatures and event definition using the code below: //add statements in the custom control constructor this .Parent.Click += new EventHandler(Parent_Click); this .Parent.Move += new EventHandler(Parent_Click); //event body private void Parent_Click( object sender, EventArgs e) { _dropDown.Close(); //ToolStripDropdown object } Cheers!

Focus Or Caret On TextBox Control Gone If ToolstripDropdown Is shown In Custom Controls Windows Forms C#

Im trying to implement a custom textbox control with auto-suggest features. Upon rendering the ToolStripDropdown object just below the textbox control, the focus seems to be lost. I found the trick by setting the AutoClose property to false in the Textbox OnHandleCreated(EventArgs e) event. See the code below: _dropDown.AutoClose = false ; //ToolStripDropDown object Greg

Accessing App.Config Values In Class Library Not Working In C#

In a project that we are working with involves several class libraries. And one of them involves setting/getting the connection string. We simply added an application config file with the connection string in it. However, accessing the key/value of connection string returns null. One possible solution is to add a Settings file in the class library where you can set the connection string. And to access the connection string value, refer to the code below: //Settings is the Settings File. //SalesConnection is the Name of the connection string return new Settings().SalesConnection; Here's a similar post regarding Settings File: Setting app.config in ASP.NET Cheers!

Combobox With CheckListBox Supports Multi highlighting (C#)

Image
A control developed by: Stelios Alexandrakis which I found it cool is a combobox with checklistbox as the dropdown item. After fixing a few bugs, I integrate the feature of multi-highlighting based from the previous post on customizing CheckListBox control: CheckBoxList Multihighlight . Here's some screenshots to illustrate each of the custom controls.

CheckBoxList Control With Multi-Highlighting Support In C# Windows Forms

Image
If you want to customize the CheckBoxList control to support multi-highlighting (each checked item is highlighted), you can simply override the OnDrawItem() by adding Graphics statements as shown below: Here's an image sample of the extended CheckBoxList control: Code: protected override void OnDrawItem(DrawItemEventArgs e) { int index = e.Index; if ( this .GetItemCheckState(index) == CheckState.Checked) { string text = this .Items[index].ToString(); Graphics g = e.Graphics; Point point = this .GetItemRectangle(index).Location; point.X += estimated_point; //estimated point is a value you may set manually //background: SolidBrush backgroundBrush; backgroundBrush = reportsBackgroundBrushSelected; //estimated point is a value you may

Pass By Reference Not Allowed In UI Threading Of Windows Forms In C#

The code below does not allow pass by reference to be used in UI threading particularly method Invoker. private void ShowPassMeta( ref int passedSound) { if (lblPassSoundex.InvokeRequired) { lblPassSoundex.Invoke((MethodInvoker) delegate { ShowPass( ref passedSound); }); } else { lblPassSoundex.Text = (++passedSound).ToString(); } } The solution is to store the method parameter in another variable as shown below: private void ShowPassMeta( ref int passedSound) { var passedSound1 = passedSound; if (lblPassSoundex.InvokeRequired) { lblPassSoundex.Invoke((MethodInvoker) delegate { ShowPassMeta( ref passedSound1); }); } else { lblPassSoundex.Text = (++passedSound1).ToString(); } } Cheers!

Donate