powershell,checkbox,datagridview , Selecting and highlight a DataGridView row by checking a checkbox


Selecting and highlight a DataGridView row by checking a checkbox

Question:

Tag: powershell,checkbox,datagridview
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "testform"
$Form.Size = New-Object System.Drawing.Size(250,300)
$Form.StartPosition = "Centerscreen"

$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Size(50,100)
$button.Size = New-Object System.Drawing.Size(140,30)
$button.Text = "Click Here"
$button.Add_Click({[void] $form1.ShowDialog()})
$Form.controls.Add($button)

$form1 = New-Object System.Windows.Forms.Form
$form1.Size = New-Object System.Drawing.Size(500,600)
$Form1.Text = "Select row by checking checkbox test"
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(400,500)

$form1.Controls.Add($dataGridView)
$dataGridView.ColumnCount = 2
$dataGridView.ColumnHeadersVisible = $true
$dataGridView.Columns.Insert(0, (New-Object System.Windows.Forms.DataGridViewCheckBoxColumn))
$dataGridView.Columns[0].Name = "select"
$dataGridView.Columns[1].Name = "column1"
$dataGridView.Columns[2].Name = "column2"


$dataGridView.Rows.Add($null, "test", "test2")
$dataGridView.Rows.Add($null, "test3", "test4")

$dataGridView.AllowUserToAddRows = $false
$dataGridView.AllowUserToDeleteRows = $false
$dataGridView.Columns["column1"].ReadOnly = $true
$dataGridView.Columns["column2"].ReadOnly = $true

[void] $Form.ShowDialog()

This simply creates a datagridview with a column of checkboxes, what I want is when a checkbox gets checked, the corresponding row gets selected and highligthed, but I don't know how to accomplish that.


Answer:

To highlight a row, you just need to set the Selected property to $true:

$dataGridView.Rows[$n].Selected = $true

To do it when a checkbox is checked, we'll need to add some code to handle the selection when a corresponding event occurs.

According to the documentation for the DataGridView.CellClick event (emphasis added):

For clicks in a DataGridViewCheckBoxCell, this event occurs before the check box changes value, so if you do not want to calculate the expected value based on the current value, you will typically handle the DataGridView.CellValueChanged event instead. Because that event occurs only when the user-specified value is committed, which typically occurs when focus leaves the cell, you must also handle the DataGridView.CurrentCellDirtyStateChanged event. In that handler, if the current cell is a check box cell, call the DataGridView.CommitEdit method and pass in the Commit value.

So, we can simply adapt the example from the documentation page for the DataGridView.CurrentCellDirtyStateChanged event:

$dataGridView.Add_CurrentCellDirtyStateChanged({
    param($Sender,$EventArgs)

    if($Sender.IsCurrentCellDirty){
        $Sender.CommitEdit([System.Windows.Forms.DataGridViewDataErrorContexts]::Commit)
    }
})

$dataGridView.Add_CellValueChanged({
    param($Sender,$EventArgs)

    if($EventArgs.ColumnIndex -eq 0){
        $Sender.Rows[$EventArgs.RowIndex].Selected = [bool]$Sender.Rows[$EventArgs.RowIndex].Cells[$EventArgs.ColumnIndex].Value
    }
})

If you want to keep multiple rows Selected, loop over each row instead:

$dataGridView.Add_CellValueChanged({
    param($Sender,$EventArgs)

    if($EventArgs.ColumnIndex -eq 0){
        foreach($RowIndex in 0..($Sender.Rows.Count - 1)){
            $Sender.Rows[$RowIndex].Selected = [bool]$Sender.Rows[$RowIndex].Cells[$EventArgs.ColumnIndex].Value
        }
    }
})

$dataGridView.MultiSelect   = $true
$dataGridView.SelectionMode = [System.Windows.Forms.DataGridViewSelectionMode]::FullRowSelect

enter image description here


Related:


PowerShell logic to remove objects from Array


arrays,powershell
I'm trying to remove objects from an array that contain duplicates and only keep the ones with the highest number in TasteCode. The example below is highly simplified, but it shows the problem. Example: $Fruits Name | Color | TasteCode ----- ------ --------- Apple | Red | 2 Apple |...

sortable check boxes with a tag


javascript,jquery,html,jquery-ui,checkbox
hi bit of a noob to this, but is it possible to have 3 check boxes and hide my a tag when one is checked but the if checkbox 2 is checked it hides that as well then when you uncheck checkbox 1 it will still stay hidden if the...

Enhancing the pipeline's content?


powershell,powershell-v3.0
Let's assume that you have a command that compresses files using 7-zip that accepts values from the pipeline: Function New-Archive { [CmdletBinding()] param ( [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)][Alias('FullName')] [string[]]$Files, [string]$Archive='Archive.zip' ) BEGIN {} PROCESS { Foreach ($File in $Files) { & 7z a -tZIP $Archive $File } } END {} } Assuming the...

aligning hierarchical checkboxes


html,css,checkbox
I am not good with CSS. I am not sure how to align checkboxes in columns with their child checkboxes underneath as a hierarchical representation. Example, I have countries and their respective states to be shown in a hierarchy but in columns as shown in the image below. I am...

Search for certain UPN suffix


powershell,active-directory
How do I search AD users by UPN suffix in AD? The users are under Uofguelph/SEC213/users OU. Some users have @sec213.com suffix and some have @home.sec213.com suffix. I need to search for users who only have @sec213.com suffix. I have the following two code snippets. Code 1 gets all accounts...

Having problems while trying to delete single rows from a custom ToDo list?


android,android-fragments,checkbox,android-studio
I want to delete selected rows from a todo list by clicking on the checkbox and deleting them trough the delete button, for that I am within my custom adapter setting a setOnCheckedChangeListener on my checkbox and setOnClickListener on my delete button, now keep in mind that the delete button...

Logging actual error when script fails


powershell,automation,error-logging
I have a script here that reads a list of computers and changes the administrator password. When the script is ran, it'll have a log file that says whether the task succeeded or fail. But I also want to log the actual error to the log when it fails. How...

Increment Serial Number using EXIF


windows,powershell,command-line,exif,exiftool
I am using ExifTool to change the camera body serial number to be a unique serial number for each image in a group of images numbering several hundred. The camera body serial number is being used as a second place, in addition to where the serial number for the image...

Turn environment variable into an array


powershell
I need to pass an array to a PowerShell subprocess and was wondering how I can turn an environment variable (string) into a PowerShell array. Is there a convention I need to follow so PowerShell will do it for me automatically or I just need to parse it myself? I'm...

PowerShell Where-Object $_.name -like -in $list


powershell
New to PowerShell and ran into a bit of a road block. I am trying to pull program name and version information from multiple servers. I have a list of the program names in a $list variable but the program names also contain the version numbers in them. I am...

Define an array with prefixes using the range operator


arrays,powershell
From this I can see I can do this with range operator: $myArray = @(4..9) But how can I do something like this: $myArray = @(usr4..9) I have tried various deviations of this with nonsense errors: $myArray = 4..9 | %\{ "usr$_"\} ...

Can I uniquely identify 2 check boxes so that I can add a different image to each?


html,css,asp.net,checkbox
Currently I am using an image for checked and unchecked checkboxes the html and css is below. <div class="text-field-box text-field-box-mobile radio-button-box small"> <asp:CheckBox ID="ChkOffer1" text=" " runat="server" class="checkbox checkbox-mobile radio" Visible="true" EnableViewState="true"></asp:CheckBox> <% Response.Write(Session("Offer1"))%> </div> and css input[type=checkbox] { display:none; } input[type=checkbox] + label { background-image: url("checkbox-default.png"); background-repeat: no-repeat;...

Format a command in powershell including a comma, can't find the right way to escape


powershell,batch-file,escaping,powershell-v2.0,comma
I have a command that I need to run in a Powershell script, the command is : ".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" | invoke-expression The comma (,) in here :[email protected],com is not a mistake, and that's what is giving me the hard time. I tried to escape the comma with `...

Powershell workflow - Get-Service not filtering


powershell,workflow
I am trying to restart Windows services in parallel via Powershell workflow. When I use Get-Service -DisplayName "S*" outside of workflow I get expected results. However, when I use the same in workflow, I get ALL services instead. It seems that -Displayname parameter is ignored in workflow. How do I...

Load page and input values


javascript,checkbox
Is it possible somehow to open url, without loading it. Let me explain, I'm creating check-box which will let to create new log and automtically input values. I know how to take boxes and input value into them using javascript. But i don't know how to open that page without...

android checkbox drawable crashing app


android,checkbox
i'm kinda new to android and i am following other questions and answers on stack overflow and i feel like i am getting close, But i can't get it to work. when i tried it crashes my app. just to test it's functionality i am using and and my code...

Using --check on a md5sum command generated checksum file is failing


powershell,cygwin,md5sum
I'm encountering an error when I try and run md5sum -c on a checksum file I generated. I should mention that I'm running this from PowerShell (as a script will be running this eventually) and this is the cygwin version of md5sum. I have a test file, jira_defect.txt and I've...

PowerShell XML formatting issue


xml,powershell
I'm having trouble getting a properly formatted XML file using the following code: # Get Computer System info $CompInfo = Get-WmiObject Win32_ComputerSystem $CompName = $CompInfo.Name # Get IP Address $IPAddressTemp = Test-Connection $CompName -count 1 | select Address,Ipv4Address $IPAddress = $IPAddressTemp.IPV4Address # Begin Writing values to XML Document $filePath =...

How to add checkbox to uicollectionview in swift


swift,checkbox,uicollectionviewcell
some time ago someone already asked this question and a few answers were given but i didn't really understand any of them. So i was wondering if anyone could please write an easy to understand tutorial on how to do the things shown on the image below: http://i.imgur.com/BzIBOkH.jpg?1 I would...

Get IP address of the Network Adapter of a computer having No gateway


powershell,ip-address,gateway
I've a project to add persistent routes on a list of servers which I need to do through Powershell. Our environment has 2 NIC's for every server , one production one backup. For this I need to fetch the Backup IP address of the computer , replace the last octet...

Programmatically accessing TFS history [closed]


c#,.net,powershell,tfs
I have a solution under TFS source control and had written some sample code using an external library that was deleted a few months ago. I am certain that the code was checked in before that class file was deleted. I am able to manually browse to previous versions of...

Issue filtering out certain event logs from output


html,powershell
So I've coded a little script that sends me the last 24 hours event logs for my Servers in a nice HTML Email to save me having to log on to each Server, etc. It works well except some of our applications produce loads of events that I want to...

Get list of files whose creation date is greater than some date time


powershell,windows-server-2012
I have a date 2015/05/28 I want to list all files using order by creation date whose creation date is greater than that using PowerShell. How could I do that? I googled for it and found Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" but no idea how to compare it with creation date...

Color a cell on the basis of another cell value


html,powershell,powershell-v2.0
I have a file output.txt having below content: SERVER_NAME MOUNT_POINT TOTAL_SPACE USED_SPACE USED_PERCENTAGE AVAILABLE_SPACE Server_1 /dev 1200G 537G 54% 464G Server_2 /dev 600G 490G 85% 94G Server_3 /dev 600G 402G 69% 181G Backup_server /storage 800G 682G 72% 278G Using following script, I formatted my output.txt file to get a notification...

Join SQL query Results and Get-ChildItem Results


sql-server,sql-server-2008,powershell
Background: I have a directory with a number of files that are imported to SQL server. Task: Creating a PowerShell script which will pick up files within this directory and use the filenames as in the SQL query. Ultimate objective: To display SQL results besides the filenames but the resultset...

Filter and delete Registry values with Where-Object


powershell,registry
I'm not sure why I'm finding this so difficult. From under a particular registry key, I'd like to query certain registry-values based on their data (not name), and delete the resulting registry-values. For example: How would I delete any values in this key that contain, let's say, "foo". I can...

How to create a powershell script that triggers a NuGet Update-Package –reinstall?


powershell,nuget-package
I have a nuget spec that installs both library file (dll) and two zip packages on a specific folder. Updating the packages is no issue when doing it from Visual Studio 2013 manually. However, when it is being triggered from either our CI servers TeamCity and CCNet, it is only...

checkbox updating another checkbox on different form


javascript,checkbox
my first javascript is not working, hope you can help. I am trying to make a checkbox on one form check a checkbox on another form. This is based on this link: check/uncheck checkbox based on another checkbox Here is my simplified code <formname="A" action="WebPage.php" method="POST"> <input type="checkbox" name="Aa" onchange="update()"...

Why does piping Get-PSSession to Exit-PSSession not work?


powershell
I'm creating a new Powershell session like so: New-PSSession -ConnectionUri https://myserver:12345 -Credential myserver\username -Authentication default This is working fine, I can do Get-PSSession and it provides me with that one session. However, when trying to pipe the result to Exit-PSSession things go haywire. So this: Get-PSSession | Exit-PSSession Or this:...

How to get checked checkboxes number with JS/HTML?


javascript,html,checkbox
I want to add a JS function in my HTML, when more than 0 checkboxes are checked, will be display a dark window in website top with actions to do (case it's bigger than 1, no function will be occurred). And when there're no checked checkboxes (lower than 1), the...

Powershell Reading text file


powershell,text,text-files
I'm just wondering if it's possible to read the content of text file with specific index? What I mean is like this, for example: I have text file like this, 'test1.txt' 12345678900 ## ## readthistext 54321123440 ## ## hellothistext I just want to read the content of text file after...

Send email with body consisting of objects


email,powershell,foreach
I am trying to write a script to search through AD and look for any stale computers and then sends an email to me. However, there are 3 requirements: get the lastlogondate for any pc that is older than 90 days once I get that list, I do a ping...

Post messages from async threads to main thread in F#


.net,powershell,f#,system.reactive,f#-async
There is a subscription to an observable that sends out log messages. Some of the log messages come from other threads because they are are in F# async blocks. I need to be able to write out the messages from the main thread. Here is the code that currently filters...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?


windows,git,powershell,github,go
I try to use go get gopkg.in/fatih/pool.v2 to install pool according to Readme.md, but can't success: C:\Users\xiaona\Documents\GitHub> go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 https fetch failed. Fetching http://gopkg.in/fatih/pool.v2?go-get=1 import "gopkg.in/fatih/pool.v2": http/https fetch: Get http://gopkg.in/fatih/poo l.v2?go-get=1: dial tcp 107.178.216.236:80: ConnectEx tcp: A connection attempt failed because the connected party did not...

Loop Issue - Remote Server


powershell
I wrote a small script to get some basic information off a few remote servers. But my output it is a bit odd. I believe my issue is with my $DRIVE function. Code: $serversList = 'svr01.xxx.com', 'svr03.xxx.com', 'svr05.xxx.com', 'svr06.xxx.com', 'svr08.xxx.com' #End of Server List Write-Output "Start of Hal0 `n"; ForEach...

How to retrieve the name and path of VM's through powercli


powershell
am using the below script to retrieve the NAME and PATH of the VM's and in the PATH am getting the full length path which i dont want it, i just need the path which is displaying after the Resources in the output here is my code: function Get-Path{ param($Object)...

select all checkbox and have the value of checked checkbox to 'on' jquery


javascript,jquery,html,checkbox
This is my fiddle for selecting from 3 checkbox. I want to have the value of selected checkbox to on while the unchecked are value off. I write the default value to off and tried to change the value of checked to on. Any suggestion is appreciated

Check a checkbox in a table row where a “delete” icon has been clicked on using JQuery


jquery,checkbox
First, I'd want to tell that i'm not a native speaker so please forgive me my mistakes. Also, this is my first time posting here. Here we go. I've searched for days everywhere (especially here) the mistakes i could have made in my code. It's probably a very stupid...

How do I select a string from a string and replace it in powershell?


powershell
I'm trying to write a powershell instance that finds and replaces each instance of text and replaces it. UserRights "rights_wo_view" I need to place parenthesis around the quotes. I've been trying all kinds of things, but I'm running flat. $files = get-item C:\Users\programmer\Documents\Project\tsbrick\*.asp foreach ($file in $files) {(Get-Content $file) select-string...

PS pipe WorkingSet as variable


variables,powershell
I have this which gives me the WorkingSet memory usage I'm after: $mem=Get-Process spiceworks | Select-Object Name,@{Name='WorkingSet';Expression={($_.WorkingSet/1KB)}} But I'm looking to only have the actual amount as the variable so I can then work with that to monitor it. I want to set it so it alerts me if it...

Event on dynamically created checkbox asp.net


c#,jquery,asp.net,table,checkbox
I started to programming with asp.net, I have a table with some checkboxses. The problem is, I can't create static tables, because this action is linked with some parameters. Anyway.. When I click on the First checkbox I want to invert the other checkboxes in this table. How can i...

Remove all folders .old


powershell
I'm trying to delete all folders in \\kiewitplaza\vdi\Appsense_profiles that end with .old. The piece I have that says Write-Host $name is just me trying to test before I delete anything. $name = Get-ChildItem "\\kiewitplaza\vdi\Appsense_profiles" if ($name.name.EndsWith(".old")) { Write-Host $name #Remove-Item "\\kiewitplaza\vdi\Appsense_profiles\$name.old" } ...

Extract e-mail from grouped objects


powershell
I have some code that pull user accounts from an OU in AD. I am sorting it using Group-Object so I know how many users are using the same email address. Code below, the $OuUser uses Get-ADUser with Properties and Filter set to *. $Duplicates = $OUUser | Select samaccountname,...

PowerShell - Convert CSV to XLSX


powershell
I found this script on here, please help me understand this better. What is the whole "gps" part of the script for? What part of this script is overwriting my original CSV and copying in the PC's taskmanager list? Processes. What does this do, why 51? ($xlOut,51) I went searching...

What is the `.` shorthand for in a PowerShell pipeline?


powershell
I'm looking over a block of code I've used (sourced from another question) and I haven't been able to figure out what the . in .{process represents in this snippet (comments removed): Get-ItemProperty $path | .{process{ if ($_.DisplayName -and $_.UninstallString) { $_ } }} | Select-Object DisplayName, Publisher, InstallDate, DisplayVersion,...

CPU usage missing from log for some processes


powershell
I'm trying to get information on all processes and services and save it into a .log. Here my Problem: Some processes have noting inside the CPU table, there I want to add something like "Nothing". How can I achieve that? That is my code so far: $ProcessTable = @{Expression={$_.ProcessName};Label="ProcessName";Width=40}, @{Expression={$_.CPU};Label="CPU";Width=20}...

How to pass a switch variable?


powershell,parameter-passing
& "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" ` -Verbose -ProjectFilePath $project -PO "$packOptions" -NPFPPTNG So if I provide the command line above in PowerShell the call works correctly. If I try something like this: if ($NoPromptForPushPackageToNuGetGallery) { $xtraOptions += " -NPFPPTNG " } & "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" ` -Verbose -ProjectFilePath $project -PO "$packOptions"...

FX - Suggestions for aligning CheckBox in Grid


java,checkbox,javafx,grid,alignment
Converting from Swing to FX here. We have some CheckBoxes where the Label appears on the left side of the CheckBox. We are accomplishing this by calling setNodeOrientation(NodeOrientation.RIGHT_TO_LEFT); The problem is that in some GridPanes, we'll have a Label in column 0 with a Node in column 1 on row...

How do I write a loop to read text file and insert it to the database


sql-server,loops,powershell
I'm writing a powershell script to load text files from a specific folder into SQL server database, I have manage to do so but only one file by one file. I want the program to do this automatically once the user inputs the path and the file extension. For example:...

Passing checkboxes values to view in django


django,checkbox,django-templates,django-views
I have a table with some database data <table id="id_list_table" class="table table-condensed"> <caption>Inputs list</caption> <thead> <tr> <th>#</th> <th id="input">Input</th> </tr> </thead> <tbody id="fbody"> {%for input in InputsAll%} <tr> <td>{{ input.input }}</td> <td> <a class="btn btn-primary btn-xs" href="{% url 'edit' %}?input_num={{input.id}}" id="edit">edit</a> <a class="btn btn-danger btn-xs" href="{% url 'delete'...