The code below inserts user details and an individual record id (querystring) into a table. This is working fine. However what i'm trying to do is add a condition that a checkbox must be checked also and this will determine which of the rows (records) in
the gridview are to be inserted into the table.
This on the outset seems to be a very simple task however after a couple of hours still can't get it to work and don't seem to have any errors to help me figure it out!
Protected Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim myTrain As String = Request.QueryString("NewTrainId")
If myTrain IsNot Nothing Then
Dim strQuery As String
Dim cmd As SqlCommand
For Each rowItem As GridViewRow In GridView1.Rows
Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden)
Dim userID As Guid = New Guid(lblUsr2.Value().ToString)
Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId")
strQuery = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("@UserId", userID)
cmd.Parameters.AddWithValue("@NewTrainId", myTrain)
InsertUpdateData(cmd)
End If
Next
End If
End Sub
Assuming each row has checkbox conrol with id "check_box" following is one of the ways to accomplish this.
Below is the vb.net code:
Protected Sub BtnClick_GetFavourites(sender As Object, e As EventArgs)
Dim CheckedIDs As IEnumerable(Of String) = From row In GridView.Rows Where DirectCast(row.FindControl("check_box"), CheckBox).Checkedrow.Cells(1).Text
For Each id As String In CheckedIDs
If Not favouritesList.Items.Contains(New ListItem(id)) Then
favouritesList.Items.Add(id.ToString())
End If
Next
End Sub
One possible solution may be as below:
This solution actually demonstrates how to:
bind dataset --- dynamically
bind Nth column who is having Checkbox --- dynamically
Bind Xth column to convert it to hyperlink --- dynamically
(2nd and 3rd are very useful if you are working with user control stuff Like for Dashboard or so)
Scenario:
gets the datasource flourished (Line 45-66 in .cs)
Inserts a cell in each row (column) containing checkboxlist as the very first column (Line 75-78 & 104-117 in .cs)
Converts the second column to hyper link, setting the target URLs dynamically and making ti to open in new window (Line 78-83 in .cs)
Finally the button click event adds the distinct "favourites" as list view (Line 92-102 in .cs)
below are some important code snips:
Protected Sub GridView_RowDatabound(sender As Object, e As GridViewRowEventArgs)
Dim cell As New TableCell()
e.Row.Cells.AddAt(0, cell)
AddCheckBox(e.Row)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim firstCell = e.Row.Cells(1)
firstCell.Controls.Clear()
firstCell.Controls.Add(New HyperLink() With { _
Key .NavigateUrl = "http://aarsh.net/" & Convert.ToString(firstCell.Text), _
Key .Target = "_blank", _
Key .Text = firstCell.Text _
})
End If
End Sub
Private Sub AddCheckBox(row As GridViewRow)
If row.RowType = DataControlRowType.DataRow Then
Dim cb As New CheckBox()
cb.ID = "check_box"
cb.ClientIDMode = ClientIDMode.[Static]
cb.Checked = False
row.Cells(0).Controls.Add(cb)
End If
End Sub
'finally the button click event ...
Protected Sub BtnClick_GetFavourites(sender As Object, e As EventArgs)
Dim CheckedIDs As IEnumerable(Of String) = From row In GridView.Rows Where DirectCast(row.FindControl("check_box"), CheckBox).Checkedrow.Cells(1).Text
For Each id As String In CheckedIDs
If Not favouritesList.Items.Contains(New ListItem(id)) Then
favouritesList.Items.Add(id.ToString())
End If
Next
End Sub
If interested to refer the entire solution, (
http://sdrv.ms/SEss7I - File name : GridFirstColumnAsCheckBoxAnd2ndAsDynamicLink_GetCheckedRows.zip - The VB.NET version of the solution has not been uploaded yet
)
For Each rowItem As GridViewRow In GridView1.Rows
Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
Modify your code like this:
Dim chkBox As CheckBox = DirectCast(rowItem.FindControl("RowLevelCheckBox"), CheckBox)
Please mark the replies as answers if they help or unmark if not.
Feedback to us
When I place the snippet in my code and attempt to insert, nothing is inserted!
When i remove the snippet
For Each rowItem As GridViewRow In GridView1.Rows
Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
This is the entire code block(s) in question. Can't for the life of me work out what im doing wrong?
Protected Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim myTrain As String = Request.QueryString("NewTrainId")
If myTrain IsNot Nothing Then
Dim strQuery As String
Dim cmd As SqlCommand
For Each rowItem As GridViewRow In GridView1.Rows
Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden)
Dim userID As Guid = New Guid(lblUsr2.Value().ToString)
Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId")
Dim chkBox As CheckBox = CType(GridView1.FindControl("RowLevelCheckBox"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
strQuery = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)"
cmd = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("@UserId", userID)
cmd.Parameters.AddWithValue("@NewTrainId", myTrain)
InsertUpdateData(cmd)
End If
Next rowItem
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim con As New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
con.Close()
con.Dispose()
End Try
End Function
Changed my insert function to this one and still no luck! This should be working! however when i submit no data is inserted.
Protected Sub btnAttend_Click(ByVal sender As Object, ByVal e As EventArgs)
For Each rowItem As GridViewRow In GridView1.Rows
Dim myTrain As String = Request.QueryString("NewTrainId")
Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden)
Dim userID As Guid = New Guid(lblUsr2.Value().ToString)
Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId")
Dim ConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim SqlString As String = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)"
Try
If rowItem.RowType = DataControlRowType.DataRow Then
Dim chkBox As CheckBox = DirectCast(rowItem.Cells(0).FindControl("RowLevelCheckBox"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked AndAlso myTrain IsNot Nothing Then
Using conn As New SqlConnection(ConnString)
Using cmd As New SqlCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@UserId", userID)
cmd.Parameters.AddWithValue("@NewTrainId", myTrain)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Else
End If
End If
Catch ex As Exception
Throw ex
End Try
Next
End Sub
When I change the querystrings condition If chkBox
IsNotNothingAndAlso chkBox.CheckedAndAlso myTrain IsNotNothingThen with
If myTrain IsNot Nothing Then
the loop works and all the records insert into the table.for some reason it's failing at the checkbox.
the loop works and all the records insert into the table.for some reason it's failing at the checkbox.
I'm really stuggling to expl;ain this one!
Hi ! Not sure if you already did, but does your markup looks just like the way I posted in my first reply ? I observed in your original question that you have cluttered some checkbox fields in <itemtemplate> tag thing. Please make sure that you follow the
example for which I've provided the code-snippets for and also the link to direct download from skydrive, I guess.
If you still believe that you are having issues even after follwoing what I suggested please spend a moment from your busy life and post the code snip.
I-Weedy
Member
67 Points
239 Posts
Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Nov 30, 2012 04:21 PM|LINK
The code below inserts user details and an individual record id (querystring) into a table. This is working fine. However what i'm trying to do is add a condition that a checkbox must be checked also and this will determine which of the rows (records) in the gridview are to be inserted into the table.
This on the outset seems to be a very simple task however after a couple of hours still can't get it to work and don't seem to have any errors to help me figure it out!
Herse my code any ideas>?
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" CssClass="rounded-corner" width="500px" AutoGenerateColumns="false"> <Columns> <asp:TemplateField Visible="false"> <ItemTemplate> <input id="txtUsr" type="hidden" runat="server" value='<%# Bind("UserId") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="chkAllIn" runat="server" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="RowLevelCheckBox" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Service No" SortExpression="serviceNo" HeaderStyle-Font-Bold="true"> <ItemTemplate> <asp:Label ID="lblmyNo" runat="server" Text='<%# Bind("myNo") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="First Name" SortExpression="forename" HeaderStyle-Font-Bold="true"> <ItemTemplate> <asp:Label ID="lblFirstName" runat="server" Text='<%# Bind("forename") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Surname" SortExpression="surname" HeaderStyle-Font-Bold="true"> <ItemTemplate> <asp:Label ID="lblSurname" runat="server" Text='<%# Bind("surname") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel>Protected Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs) Dim myTrain As String = Request.QueryString("NewTrainId") If myTrain IsNot Nothing Then Dim strQuery As String Dim cmd As SqlCommand For Each rowItem As GridViewRow In GridView1.Rows Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox) If chkBox IsNot Nothing AndAlso chkBox.Checked Then Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden) Dim userID As Guid = New Guid(lblUsr2.Value().ToString) Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId") strQuery = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)" cmd = New SqlCommand(strQuery) cmd.Parameters.AddWithValue("@UserId", userID) cmd.Parameters.AddWithValue("@NewTrainId", myTrain) InsertUpdateData(cmd) End If Next End If End Subaarsh
Participant
1543 Points
427 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Nov 30, 2012 04:57 PM|LINK
Hi !
Assuming each row has checkbox conrol with id "check_box" following is one of the ways to accomplish this.
Below is the vb.net code:
Protected Sub BtnClick_GetFavourites(sender As Object, e As EventArgs) Dim CheckedIDs As IEnumerable(Of String) = From row In GridView.Rows Where DirectCast(row.FindControl("check_box"), CheckBox).Checkedrow.Cells(1).Text For Each id As String In CheckedIDs If Not favouritesList.Items.Contains(New ListItem(id)) Then favouritesList.Items.Add(id.ToString()) End If Next End SubOne possible solution may be as below:
This solution actually demonstrates how to:
(2nd and 3rd are very useful if you are working with user control stuff Like for Dashboard or so)
Scenario:
below are some important code snips:
Protected Sub GridView_RowDatabound(sender As Object, e As GridViewRowEventArgs) Dim cell As New TableCell() e.Row.Cells.AddAt(0, cell) AddCheckBox(e.Row) If e.Row.RowType = DataControlRowType.DataRow Then Dim firstCell = e.Row.Cells(1) firstCell.Controls.Clear() firstCell.Controls.Add(New HyperLink() With { _ Key .NavigateUrl = "http://aarsh.net/" & Convert.ToString(firstCell.Text), _ Key .Target = "_blank", _ Key .Text = firstCell.Text _ }) End If End Sub Private Sub AddCheckBox(row As GridViewRow) If row.RowType = DataControlRowType.DataRow Then Dim cb As New CheckBox() cb.ID = "check_box" cb.ClientIDMode = ClientIDMode.[Static] cb.Checked = False row.Cells(0).Controls.Add(cb) End If End Sub 'finally the button click event ... Protected Sub BtnClick_GetFavourites(sender As Object, e As EventArgs) Dim CheckedIDs As IEnumerable(Of String) = From row In GridView.Rows Where DirectCast(row.FindControl("check_box"), CheckBox).Checkedrow.Cells(1).Text For Each id As String In CheckedIDs If Not favouritesList.Items.Contains(New ListItem(id)) Then favouritesList.Items.Add(id.ToString()) End If Next End SubHere is my mark-up
<asp:SqlDataSource ID="GridDataSource" runat="server"></asp:SqlDataSource> <asp:Button ID="favourites" runat="server" Text="Favourites" OnClick="BtnClick_GetFavourites" /> <asp:ListBox ID="favouritesList" runat="server"></asp:ListBox> <asp:GridView ID="GridView" runat="server" OnRowDataBound="GridView_RowDatabound"> <Columns> </Columns> </asp:GridView>If interested to refer the entire solution, ( http://sdrv.ms/SEss7I - File name : GridFirstColumnAsCheckBoxAnd2ndAsDynamicLink_GetCheckedRows.zip - The VB.NET version of the solution has not been uploaded yet )
Or, may be, this can help :
http://aspnet.4guysfromrolla.com/articles/053106-1.aspx
anil.india
Contributor
2613 Points
453 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Nov 30, 2012 05:47 PM|LINK
You can use the power of jQuery with JavaScript and ASP.Net.
if you want to select all checkboxes on click of header checkbox then call a JavaScript function on its click event-
Also add another function on your item checkbox "RowLevelCheckBox" on its onclick event -
And for validating that user select atleas one row, you can call a function on your button btn onclientclick.
Add following script functions to your page -
<script type="text/javascript"> function ToggleAllChildCheckboxe(ctrl) { $('[id$=RowLevelCheckBox]').attr('checked', ctrl.checked); } function ToggleAllChildCheckboxe(ctrl) { if ($('[id$=RowLevelCheckBox]').length == $('[id$=RowLevelCheckBox]:checked').length) $('[id$=chkAllIn]').attr('checked', true); else $('[id$=chkAllIn]').attr('checked', false); } function ValidateForMinimumOneCheckBox() { if ($('[id$=RowLevelCheckBox]:checked').length < 1) { alert('Please select atleast one row !'); return false; } else return true; } </script>codepattern.net/blog ||@AnilAwadh
Frank Jiang ...
All-Star
16006 Points
1728 Posts
Microsoft
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 03, 2012 04:37 AM|LINK
Modify your code like this:
Dim chkBox As CheckBox = DirectCast(rowItem.FindControl("RowLevelCheckBox"), CheckBox)
Feedback to us
Develop and promote your apps in Windows Store
I-Weedy
Member
67 Points
239 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 03, 2012 09:33 AM|LINK
This does exactly the same as my previous code!
When I place the snippet in my code and attempt to insert, nothing is inserted!
When i remove the snippet
For Each rowItem As GridViewRow In GridView1.Rows Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox) If chkBox IsNot Nothing AndAlso chkBox.Checked Thenfrom the code it inserts all of the records
I-Weedy
Member
67 Points
239 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 04, 2012 12:48 PM|LINK
This is the entire code block(s) in question. Can't for the life of me work out what im doing wrong?
Protected Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs) Dim myTrain As String = Request.QueryString("NewTrainId") If myTrain IsNot Nothing Then Dim strQuery As String Dim cmd As SqlCommand For Each rowItem As GridViewRow In GridView1.Rows Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden) Dim userID As Guid = New Guid(lblUsr2.Value().ToString) Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId") Dim chkBox As CheckBox = CType(GridView1.FindControl("RowLevelCheckBox"), CheckBox) If chkBox IsNot Nothing AndAlso chkBox.Checked Then strQuery = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)" cmd = New SqlCommand(strQuery) cmd.Parameters.AddWithValue("@UserId", userID) cmd.Parameters.AddWithValue("@NewTrainId", myTrain) InsertUpdateData(cmd) End If Next rowItem End If End SubPublic Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConString").ConnectionString Dim con As New SqlConnection(strConnString) cmd.CommandType = CommandType.Text cmd.Connection = con Try con.Open() cmd.ExecuteNonQuery() Return True Catch ex As Exception Response.Write(ex.Message) Return False Finally con.Close() con.Dispose() End Try End Functionany help would really be appreciated.
Frank Jiang ...
All-Star
16006 Points
1728 Posts
Microsoft
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 05, 2012 12:55 AM|LINK
Hi,
Do you replace "GridView1" with rowItem variable in the line below?
Dim chkBox As CheckBox = DirectCast(GridView1.FindControl("RowLevelCheckBox"), CheckBox)
Feedback to us
Develop and promote your apps in Windows Store
aarsh
Participant
1543 Points
427 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 05, 2012 04:38 AM|LINK
I-Weedy, did you got a chance to try what did I suggested ?
I-Weedy
Member
67 Points
239 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 06, 2012 12:38 PM|LINK
Yes i did and still no resolution!
Changed my insert function to this one and still no luck! This should be working! however when i submit no data is inserted.
Protected Sub btnAttend_Click(ByVal sender As Object, ByVal e As EventArgs) For Each rowItem As GridViewRow In GridView1.Rows Dim myTrain As String = Request.QueryString("NewTrainId") Dim lblUsr2 As HtmlInputHidden = CType(rowItem.FindControl("txtUsr"), HtmlInputHidden) Dim userID As Guid = New Guid(lblUsr2.Value().ToString) Dim HidTrainId As HtmlInputHidden = FindControlRecursive(MultiTabs, "txtTrainId") Dim ConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConString").ConnectionString Dim SqlString As String = "Insert into userAssessmentTbl(tt_id, UserId)values(@NewTrainId, @UserId)" Try If rowItem.RowType = DataControlRowType.DataRow Then Dim chkBox As CheckBox = DirectCast(rowItem.Cells(0).FindControl("RowLevelCheckBox"), CheckBox) If chkBox IsNot Nothing AndAlso chkBox.Checked AndAlso myTrain IsNot Nothing Then Using conn As New SqlConnection(ConnString) Using cmd As New SqlCommand(SqlString, conn) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@UserId", userID) cmd.Parameters.AddWithValue("@NewTrainId", myTrain) conn.Open() cmd.ExecuteNonQuery() End Using End Using Else End If End If Catch ex As Exception Throw ex End Try Next End SubWhen I change the querystrings condition If chkBox IsNot Nothing AndAlso chkBox.Checked AndAlso myTrain IsNot Nothing Then
with
If myTrain IsNot Nothing Then
the loop works and all the records insert into the table.for some reason it's failing at the checkbox.
I'm really stuggling to expl;ain this one!
aarsh
Participant
1543 Points
427 Posts
Re: Retrieve Rows Selected Using CheckBox in an ASP.NET GridView
Dec 07, 2012 03:39 AM|LINK
Hi ! Not sure if you already did, but does your markup looks just like the way I posted in my first reply ? I observed in your original question that you have cluttered some checkbox fields in <itemtemplate> tag thing. Please make sure that you follow the example for which I've provided the code-snippets for and also the link to direct download from skydrive, I guess.
If you still believe that you are having issues even after follwoing what I suggested please spend a moment from your busy life and post the code snip.
Thanks !