Two ways of binding data to a GridView (ASP.NET)

In the following example, I will show you how to bind the same field to an ASP.NET GridView using two different methods.

In the first example, I utilize the an asp:BoundField to display the data, whereas in the second example I utilize an asp:TemplateField

Example 1 – BoundField:

[vb]

<asp:BoundField DataField=”ORDER_NUMBER” HeaderText=”Order” ReadOnly=”True” SortExpression=”ORDER_NUMBER” ItemStyle-Wrap=false />

[/vb]

Example 2 – TemplateField:

[vb]

<asp:TemplateField HeaderText=”Order” SortExpression=”OrderLineSched” ItemStyle-Wrap=”false”>
<ItemTemplate>
<asp:Label ID=”OrderLineSched” runat=”server” Text='<% #Bind(“ORDER_NUMBER”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>

[/vb]

Both will display exactly the same, however the TemplateField provides greater flexibility because if, for example, you change the field type from Label to TextBox, you can make it an editable field that will actually be editable in the entire GridView (all rows).

Detect Double Right Mouse Click (VB.NET)

Simple Black Ops 2 countdown timer that’s triggered/dipslayed when the user double right-clicks the status bar in an application.  #easteregg

[vbnet]

Private Sub StatusStrip1_MouseDoubleClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles StatusStrip1.MouseDoubleClick
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim dt_BO2Launch As Date = “11/13/2012 00:00:00”
Dim tspan As TimeSpan = dt_BO2Launch.Subtract(Now)
MessageBox.Show(tspan.Days & “:” & tspan.Hours & “:” & tspan.Minutes & “:” & tspan.Seconds & vbCrLf & “DD:HH:MM:SS”, “Time until Black Ops 2 Launch!”, MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
End Sub

[/vbnet]

Increase/Decrease Textbox Font Size Programatically (VB.NET)

[vbnet]
Private Sub frm_Main_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
‘ Ctrl + + = increase the SQL size
If e.Control And e.KeyCode = Keys.Add Then
Using f As Font = TextBox1.Font
TextBox1.Font = New Font(f.FontFamily, f.Size + 1, f.Style)
End Using
Exit Sub
End If

‘ Ctrl + – = decrease the SQL size
If e.Control And e.KeyCode = Keys.Subtract Then
Using f As Font = TextBox1.Font
TextBox1.Font = New Font(f.FontFamily, f.Size – 1, f.Style)
End Using
Exit Sub
End If
End Sub
[/vbnet]

Capture when Ctrl+Enter keys are pressed at the same time (VB.NET)

Make sure your Form’s KeyPreview property is set to True.

[vbnet]
Private Sub frm_Main_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.Control And e.KeyCode = Keys.Enter Then
‘ Do something
End If
End Sub
[/vbnet]

You can also capture when the Alt+Enter keys are pressed at the same time with the following:

[vbnet]
Private Sub frm_Main_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
If e.Alt And e.KeyCode = Keys.Enter Then
‘ Do something
End If
End Sub
[/vbnet]

How to fetch data from using a BackgroundWorker (VB.NET)

BackgroundWorkers (which I will refer to as bgWorker) are great for doing background processing in your application, thus preventing your program from going into a “Not Responding” status.  One downfall, however, is that you cannot pass or reference data in a separate thread from the bgWorker.  The following code shows how to get around this by utilizing Global/Public variables because they are referenced between all threads of the application.


Global/Public Variables

[vbnet] ‘ public variables
Public dr As OdbcDataReader
Public conn As OdbcConnection

Dim miliSecond As Long = 1000
Dim timerSeconds As Long
Dim startDttm As Date
Dim endDttm As Date
Dim sqlComm As String
Dim dt As New DataTable
Dim da As New OdbcDataAdapter
Dim strConnString As String
Dim comm As OdbcCommand
[/vbnet]
How to call the BackgroundWorker
[vbnet]
bgWorker = New BackgroundWorker
bgWorker.WorkerReportsProgress = True
bgWorker.WorkerSupportsCancellation = True
bgWorker.RunWorkerAsync() ‘ run the background worker
[/vbnet]
Run the BackgroundWorker and fetch the data
[vbnet]
Private Sub FetchData(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bgWorker.DoWork
Try
Dim conn As New OdbcConnection(strConnString)
startDttm = Now()

comm = New OdbcCommand(sqlComm)
comm.Connection = conn
comm.Connection.Open()

dt = New DataTable
da = New OdbcDataAdapter
da.SelectCommand = comm ‘ Utilize the SELECT statement
da.Fill(dt) ‘ Fill the Data Table

Catch ex As Exception
MsgBox(“ERROR: ” & ex.Message, MsgBoxStyle.Critical, “Error running SQL”)
dbClose()
End Try
End Sub
[/vbnet]
What to do when the BackgroundWorker is finished
[vbnet]
Private Sub bgWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted
Try
UpdateDataGrid()

Catch ex As Exception
bgWorker.CancelAsync()
End Try
End Sub
[/vbnet]
Update the DataGridView (dg)
[vbnet]
Private Sub UpdateDataGrid()
Try
Dim intCount As Integer
intCount = dt.Rows.Count ‘ number of rows returned by SQL

Select Case intCount
Case Is < 1000 ‘ fill if less than 1000 rows
Me.dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
dg.DataSource = dt ‘ Populate the Data Grid with the Data Table values
dr = comm.ExecuteReader
Case Else
If MsgBox(“This will display ” & Format(dt.Rows.Count, “###,###,##0″) & ” rows. Would you like to continue?”, MsgBoxStyle.YesNo, “Continue?”) = MsgBoxResult.Yes Then
Me.dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
dg.DataSource = dt ‘ Populate the Data Grid with the Data Table values
dr = comm.ExecuteReader
End If
End Select

dbClose()

dg.AutoResizeColumns()

If comm.ExecuteNonQuery >= 0 Then
intCount = comm.ExecuteNonQuery
End If

AddToSummary(Format(intCount, “###,###,##0″) & IIf(intCount = 1, ” record found”, ” records found”), False)

Dim dur As Global.System.TimeSpan = Now.Subtract(startDttm)
AddToSummary(” – ” & dur.Seconds & “.” & dur.Milliseconds & ” seconds”, True)

Catch ex As Exception
MessageBox.Show(“Error updating data grid”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
[/vbnet]
Close the Database Connection

[vbnet]
Private Sub dbClose()
Try ‘ Close the Data Reader
dr.Close()
dr = Nothing
Catch ex As Exception
‘MsgBox(“Error closing the data reader” & vbCrLf & ex.Message, MsgBoxStyle.Critical, “Data Reader Close Issue”)
End Try

Try ‘ Close the Connection
conn.Dispose()
conn = Nothing
Catch ex As Exception
MsgBox(“Error closing the connection” & vbCrLf & ex.Message, MsgBoxStyle.Critical, “ODBC Connection Close Issue”)
End Try
End Sub
[/vbnet]
Add to Summary method – I use a TextBox (txt_Status) on my Form for displaying application status to the user
[vbnet]
Private Sub AddToSummary(ByVal strText As String, ByVal Append As Boolean)
If Append Then
Me.txt_Status.Text += strText
Else
Me.txt_Status.Text = strText
End If
End Sub
[/vbnet]

How to check/uncheck “child” nodes in a TreeView (C# & VB.NET)

Call this method from within your TreeView’s “AfterCheck” event. Pass it the AfterCheck event’s “sender” and “e” parameters.

C#
[csharp]
private void CheckChildren(object sender, TreeViewEventArgs e)
{
bool boolChecked = e.Node.Checked;

if (e.Node.Parent == null) // parent node
{
foreach (TreeNode node in e.Node.Nodes)
node.Checked = boolChecked;
}
}
[/csharp]

VB.NET:
[vbnet]
Private Sub CheckChildren(sender As Object, e As TreeViewEventArgs)
Dim boolChecked As Boolean = e.Node.Checked

If (e.Node.Parent Is Nothing) Then ‘ parent node
For Each tn As TreeNode In e.Node.Nodes
tn.Checked = boolChecked
Next
End If
End Sub
[/vbnet]

Copy Selected DataGridView Cells to Clipboard

To copy selected cells to the Clipboard without Column Headers:

If dg.GetClipboardContent Is Nothing Then

MessageBox.Show(“Nothing selected to copy to clipboard.”)

Else

Me.dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

Clipboard.SetDataObject(Me.dg.GetClipboardContent)

End If

 

To copy selected cells to the Clipboard with Column Headers requires a bit more work because there is a leading tab/column that needs to be removed:

If dg.GetClipboardContent Is Nothing Then

MessageBox.Show(“Nothing selected to copy to clipboard.”)

Else

Me.dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

Dim clipData As String = dg.GetClipboardContent.GetText()

Dim lines As String() = Regex.Split(clipData, “rn”)

Dim newClipData As New StringBuilder

Dim tab As Char = vbTab

For Each line As String In lines

newClipData.Append(line.Substring(line.IndexOf(tab) + 1) + vbCrLf)

Next

Clipboard.SetText(newClipData.ToString(), TextDataFormat.Text)

End If

Remove item from ArrayList in a FOR loop (VB.NET)

Today I was trying to loop through an ArrayList (AL) that I had saved as a User Setting and remove values from the related AL that matched a specific value.  However, I was receiving the error, “Collection was modified; enumeration operation may not execute.”  This was because I was trying to remove an item from the AL while iterating through a For Each statement.

For Each str_env As String In My.Settings.Env_Collection

Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(str_env)

If env.Division = div Then

My.Settings.Env_Collection.RemoveAt(i)

End If

i += 1

Next

To get around this, I tried switching over to a For statement instead, but received an Index Out of Bounds error because I used the original AL.Count() as my “stopping” point for the loop.  However, once I started removing items from the ArrayList, the Count() was less and there was no way to force my For loop to acknowledge that.  For example, if my initial Count() was 10 and I was removing 4 items, the For loop would continue up to 10 and not take into account any removed indexes; eventually, it would try to access an index that no longer existed in the ArrayList.

For i = 0 To My.Settings.Env_Collection.Count Step 1
Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(My.Settings.Env_Collection(i))
If env.Division = div Then
My.Settings.Env_Collection.RemoveAt(i)
End If
Next

To resolve, simply step backwards through the array!

For i = (My.Settings.Env_Collection.Count – 1) To 0 Step1

Dim env As Environment = GlobalVar.EnvCollection.ConvertStringToEnvironment(My.Settings.Env_Collection(i))

If env.Division = div Then

My.Settings.Env_Collection.Remove(My.Settings.Env_Collection(i))

End If

Next

Simple, yet effective!  Happy coding!

Password Mask an unbound TextBox column in a DataGridView (VB.NET)

If you have ever wanted to mask the contents in a TextBox column on a DataGridView (DGV) control, you will notice that there is no pre-defined “password” format that you can apply.  I have gotten around this by setting the DataPropertyName attribute of the column and then checking the related property in the CellFormatting event.  It’s actually pretty simple and doesn’t involve very much coding at all!

DataPropertyName = "password"

DataPropertyName = "password"

After you have set the DataPropertyName for the related column(s) in your DGV, you need to add code that will evaluate this property when the data is loaded.  For this, I will use the CellFormatting event.

Before we begin, I want to set the character that will be displayed instead of actual value.  For this, I will use an asterisk (*).

Private pwd As Char = “*”

In the below example, my DataGridView is named dg_Divisions.  This routine will store the value of any field with the DataPropertyName of “password” into the related cell’s Tag property and will change each character in the Value to an asterisk.  If the field is not a “password” field, it will set the Tag to Nothing (null).

Private Sub dgv_PwdFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles dg_Divisions.CellFormatting
If dg_Divisions.Columns(e.ColumnIndex).DataPropertyName = “passwordAnd e.Value <> Nothing Then
dg_Divisions.Rows(e.RowIndex).Tag = e.Value
e.Value = New String(pwd, e.Value.ToString.Length)
Else
dg_Divisions.Rows(e.RowIndex).Tag = Nothing
End If
End Sub
After the Tags and Values have been changed, we want the user to be able to see and modify the value if they begin editing the cell.  To do this, I will use the EditingControlShowing event.
Private Sub dgv_PwdEditing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles dg_Divisions.EditingControlShowing
If (dg_Divisions.CurrentRow.Tag <> Nothing) Then
e.Control.Text = dg_Divisions.CurrentRow.Tag.ToString()
End If
End Sub
Value displayed as asterisks

Value displayed as asterisks

Editing the cell displays the underlying contents

Editing the cell displays the underlying contents

That’s all there is to it!  Happy coding!