Loop through controls and change LINQ columns - asp.net

I have the following code:
Dim i As Integer
For i = 1 To 20
Dim captionTextBox As TextBox = DirectCast(Me.FindControl("news_Image" + i.ToString() + "CaptionTextBox"), TextBox)
Dim deleteCheckBox As CheckBox = DirectCast(Me.FindControl("Image" + i.ToString() + "DeleteCheckBox"), CheckBox)
If Not deleteCheckBox.Checked = False Then
If Not captionTextBox.Text = "" Then
'Insert the value of the textbox into the column like news_Image1Caption, news_image2Caption nased on the value of i
End If
End If
Next
Where the comment is in the code above, I need to insert the value of the textbox (text) into Linq columns. For example: articleToUpdate.news_Image1Caption, news_Image2Caption, but I need to change the number after news_ to the value of i in the for loop. How can I do this?
Thanks
Luke

Did you try to set the ID column to Auto-Generated Value = true ?
INSERT INTO [dbo].[s_Tbl]([ID], [news_Image1Caption], [news_image2Caption]) VALUES (...)

Related

get values of dynamic checkboxes

I am dynamically creating checkboxes in VB.Net and an .aspx page, based on values in my db. I'm placing them in a two column table for ease of alignment. this part works fine.
Private Async Function InitForEditAsync() As Task
Dim docList = Await GetLoanApplicationConfigurationDocs()
Dim row = New HtmlTableRow()
Dim cell = New HtmlTableCell()
Dim i = 0
For Each doc In docList
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = i Mod 2
chkBox.ID = "chkDocId" + doc.Id.ToString
lbl.Text = doc.DisplayName
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
If remainder <> 0 OrElse i = docList.Count() - 1 Then
tblEdit.Rows.Add(row)
row = New HtmlTableRow()
End If
i += 1
Next
End Function
Now I need to retrieve the values without knowing the id's but am not having any luck. I tried this:
For Each chkBox As HtmlInputCheckBox In pnlEdit.Controls.OfType(Of HtmlInputCheckBox)
but the checkboxes are not returned in the list of controls. The table is, but there are no rows in the table object when I explored it in the control collection and when I tried this:
For Each row As HtmlTableRow In tblEdit.Rows.OfType(Of HtmlTableRow)
If it will help, here is a Snip of the UI and the HTML that is created:
Any suggestions are appreciated. Thanks in advance.
Based on some ideas I got from another site, I'm going to rewrite this using the asp:CheckBoxList. apparently it binds like a datagrid and you can enumerate through it. Seems like what i need.
UPDATE: Everything I posted to start was resolved with five lines of code! "cblDocList is my asp CheckboxList and docList is my ienumerable of objects.
cblDocList.RepeatColumns = 2
cblDocList.DataSource = docList
cblDocList.DataTextField = "DisplayName"
cblDocList.DataValueField = "Id"
cblDocList.DataBind()
It’s something you can do through a loop for each row and each cell or using Linq to have only cells that have controls of type HtmlInputCheckBox inside.
I have simplified your code to be able run that here also shows you an example to achieve your task. Obviously you must change following your exigences .
Hope I well understood :)
Dim tblEdit As New HtmlTable
For k As Integer = 0 To 10
Dim cell = New HtmlTableCell()
Dim row = New HtmlTableRow()
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = k Mod 2
chkBox.ID = "chkDocId_" + k.ToString
chkBox.Checked = remainder = 0
lbl.Text = "Text indicator of CheckBox nr:" + k.ToString
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
tblEdit.Rows.Add(row)
Next
Dim checkBoxes As IEnumerable(Of HtmlInputCheckBox) =
(From mRow In tblEdit.Rows).Select(Function(mr)
Dim cb = (From cc In CType(mr, HtmlTableRow).Cells
Where CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox).Count > 0
Select CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox)()(0)).FirstOrDefault
Return CType(cb, HtmlInputCheckBox)
End Function).ToList
For Each checkBox In checkBoxes
Debug.WriteLine("CheckBox ID: {0} Checked: {1} ", checkBox.ID, checkBox.Checked)
Next

Combine Row Cell for Repeater Record

I'm trying to combine the row cells when the campaign code and vehicle no are repeated as shown in below image. The result listed below is with gridview 20 page size
Problem
When the grid view page size is set with 2 for example, the row cell no longer combined. The result show each separated record.
If campaign code is sorted ascending/descending, the last record row cells will always not combine even though the campaign code and vehicle no are matched. Below image shown campaign code sorted in ascending. So when the campaign code is sorted descending, all the CMP002 are combined, while the last record of CMP001 will not be combined as shown in below image anymore.
Code Behind
Private Sub GV_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
For rowIndex As Integer = GV.Rows.Count - 2 To 0 Step -1
Dim gvRow As GridViewRow = GV.Rows(rowIndex)
Dim gvPreviousRow As GridViewRow = GV.Rows(rowIndex + 1)
Dim sCurrCampaignCode As String = GV.DataKeys(rowIndex).Values("CAMPAIGN_CODE")
Dim sCurrVehicleNo As String = GV.DataKeys(rowIndex).Values("VEHICLE_NO")
Dim sPreviousCampaignCode As String = GV.DataKeys(rowIndex + 1).Values("CAMPAIG_CODE")
Dim sPreviousVehicleNo As String = GV.DataKeys(rowIndex + 1).Values("VEHICLE_NO")
If sCurrCampaignCode = sPreviousCampaignCode AndAlso sCurrVehicleNo = sPreviousVehicleNo Then
If sCurrCampaignCode = sPreviousCampaignCode Then
If gvPreviousRow.Cells(1).RowSpan < 2 Then
gvRow.Cells(1).RowSpan = 2
gvRow.Cells(2).RowSpan = 2
gvRow.Cells(3).RowSpan = 2
Else
gvRow.Cells(1).RowSpan = gvPreviousRow.Cells(1).RowSpan + 1
gvRow.Cells(2).RowSpan = gvPreviousRow.Cells(2).RowSpan + 1
gvRow.Cells(3).RowSpan = gvPreviousRow.Cells(3).RowSpan + 1
End If
gvPreviousRow.Cells(1).Visible = False
gvPreviousRow.Cells(2).Visible = False
gvPreviousRow.Cells(3).Visible = False
End If
End If
Next
End Sub
I just found a solution. Code have to be moved from RowDataBound to OnDataBound instead

How to build the gridview from 2 tables and save co-ordinates mapping in 3'rd table in asp.net web form?

I am having Component table, Role table, and ComponentRoleMapping table in database. Please look at the image below. I want to populate the column Component names as first column filled with all rows and roles should be the first row of grid from Role table. All cell have to have check box. The matrix co-ordinate have to save that coordination in ComponentRoleMapping table by clicking on any check box. In short to populate many to many relationship among components and Roles I need this view. I am using asp.net web form and gridview control to populate this. how to populate single gridview from 2 tables / datatables ? Or any other control I can use here. Or any article I can follow for exact purpose?
you need a RoleComponent table which is a simple table of pk's that maps a Component to a Role. Sample table:
CREATE TABLE [dbo].[RoleComponent](
[role_pk] [int] NOT NULL,
[component_pk] [int] NOT NULL
) ON [PRIMARY]
A checkbox is initially checked if an entry in this table exists for a specific role and component.
When a user:
Checks a checkbox: insert a row for the given role_pk and component_pk
UnCheck a checkbox: delete a row for the given role_pk and component_pk
To get the grid of checkboxes as you have in your display you are going to need to return a pivot table of bit fields. Pivot tables are not simple in SqlServer. In fact they are downright annoying.
A Repeater might be a better option.
I am answering my own question, It might helpful to others. Rather to use Grid control I used Html table only.
Here Dt1 has Components, Dt2 has Roles and Dt3 used for to check active status. May be some dead code in this but, running perfect.
Private Sub GenerateTable(dt2 As DataTable, dt1 As DataTable, dt3 As DataTable)
Dim table As New Table()
Dim row As TableRow = Nothing
'Add the Headers
row = New TableRow()
'Empty
Dim headerCellEmpty As New TableHeaderCell()
headerCellEmpty.Text = ""
headerCellEmpty.Attributes("style") = "border:1px solid black;text-align:center;"
row.Cells.Add(headerCellEmpty)
For i As Integer = 0 To dt2.Rows.Count - 1
Dim headerCell As New TableHeaderCell()
headerCell.Text = dt2.Rows(i)(0).ToString()
headerCell.ID = dt2.Rows(i)(1).ToString()
'Check All Components
Dim chkAllComponent As New CheckBox()
chkAllComponent.ID = "allcomponents_" + dt2.Rows(i)(1).ToString()
chkAllComponent.Text = dt2.Rows(i)(0).ToString()
headerCell.Controls.Add(chkAllComponent)
headerCell.Attributes("style") = "border:1px solid black;text-align:center;width:15%;"
row.Cells.Add(headerCell)
Next
table.Rows.Add(row)
'Add the Column values
For i As Integer = 0 To dt1.Rows.Count - 1
row = New TableRow()
For j As Integer = 0 To dt1.Columns.Count - 2
Dim cell As New TableCell()
cell.Text = dt1.Rows(i)(j).ToString()
cell.ID = dt1.Rows(i)(j + 1).ToString()
'Check All Roles
Dim chkAllRoles As New CheckBox()
chkAllRoles.ID = "allroles_" + dt1.Rows(i)(j + 1).ToString()
chkAllRoles.Text = dt1.Rows(i)(j).ToString()
cell.Controls.Add(chkAllRoles)
row.Cells.Add(cell)
Next
' Add the TableRow to the Table
table.Rows.Add(row)
Next
If table.Rows.Count > 0 Then
If table.Rows(0).Cells.Count > 0 Then
'Add check boxes
Dim allColumnsCountinTable As Integer = table.Rows(0).Cells.Count
For Each tr As TableRow In table.Rows
Dim rowIndex As Integer = table.Rows.GetRowIndex(tr)
If rowIndex = 0 Then
Else
For f As Integer = 1 To allColumnsCountinTable - 1
Dim cell As New TableCell()
Dim roleid = table.Rows(rowIndex).Cells(0).ID
Dim roleId1 As Guid = New Guid(roleid)
Dim componentid = table.Rows(0).Cells(f).ID
Dim Check1 As New CheckBox()
Check1.ID = "chk_" + roleid + "_" + componentid
Dim configurations = From p In dt3.AsEnumerable() Select p
If (configurations.Any(Function(coffee) c.Field(Of Integer)("ComponentId") = componentid And c.Field(Of Guid)("RoleId") = roleId1)) Then
Dim isActive = configurations.Where(Function(coffee) c.Field(Of Integer)("ComponentId") = componentid And c.Field(Of Guid)("RoleId") = roleId1).FirstOrDefault()("IsActive")
If isActive = True Then
Check1.Checked = True
Else
Check1.Checked = False
End If
Else
Check1.Checked = False
End If
Check1.Attributes("Name") = "checkbox"
cell.Attributes("style") = "border:1px solid black;text-align:center;"
cell.Controls.Add(Check1)
tr.Cells.AddAt(f, cell)
Next
End If
tr.Attributes("style") = "color:red; border:1px solid black;"
Next
End If
End If
'Styling
Panel1.Controls.Add(table)
End Sub

Creating a label inside Gridview Cell from VB

I have some Code in VB that is looping through a gridview's rows and is checking the values of a certain collumn, I have written some code inside the if statement that creates a clickable label inside the cell for when the cell is "", I have already written a bit of code that could create my label but I'm not too sure how it would create it inside row.Cells(8)
I was wondering if could get some assistance with how I should be doing this?...
Here's my Code:
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim row = GridView1.Rows(i)
Dim rowHeaderCell = row.Cells(8)
If rowHeaderCell.Text = " " Then
Dim lbl As New Label
lbl.Size = New System.Drawing.Size(159, 23)
lbl.Location =
lbl.Text = "label text goes here"
Me.Controls.Add(lbl)
End If
Next
Thankyou in advance!
To make a clickable label change the type of the column to : [DataGridViewLinkColumn]
here is the code to replace the Empty cell value by the value of LBL:
For i As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.Rows(i).Cells(8).Value.Trim = "" Then
Dim lbl As String
lbl = "label text goes here "
GridView1.Rows(i).Cells(8).Value = lbl
End If
Next

Looping through textboxes and labels

Im doing this project for an online test in ASP.NET in VB im using Microsoft visual studios 2012.
Im trying to get a loop going through my textboxes and check them against a word this will be change to be validated against a database to see if the answer are correct but when I do my loop I cannot get my text from the textbox.
Please see below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As Object
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Textboxname
TextboxText = textbox
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub
It looks like you are trying to use the string identifier of the control in place of the the actual control. Instead, you should take this identifier and search for the actual control on the page. You can do this using the FindControl method
Your function would therefore look something like (not compile tested):
Private Sub GoGoGo()
'
Dim oTextBox As TextBox
Dim oLabel As Label
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oTextBox = CType(Page.FindControl("TextQ" & CStr(check)), TextBox)
OTextBox.ReadOnly = True;
End If
If Currentloop <= MaxTime Then
'NB You may have to use a recursive call to FindControl. See below.
oLabel = CType(Page.FindControl("Label" & CStr(check)), Label)
oLabel.Visible = True
End If
If oTextBox.Text = "" Then
oLabel.Text = "no imput"
oLabel.ForeColor = Drawing.Color.Black
End If
If oTextBox.Text = "server" Then
oLabel.Text = "Correct"
oLabel.ForeColor = Drawing.Color.Green
End If
If oTextBox.Text = "Wrong" Then
oLabel.Text = "Wrong"
oLabel.ForeColor = Drawing.Color.Red
End If
Next
End Sub
Some notes:
You don't need all of those variables. Instead, just find the actual controls, and interact with the properties directly - just check the TextBox.Text value when you need to, and set the Label.text property directly. The set is especially important as you want to update the original control property so it is shown on the page.
Similarly, you don't need Number - you can use check as this is your loop counting variable.
Whether you use the + operator or the & operator for string concatenation is up to you. There's already a good question and several answers here.
You also don't need the exit condition for the loop - the loop will exit as soon as you reach MaxTime. If you want it to exit early, just vary your To condition (e.g. Currentloop To MaxTime - 1)
UPDATE:
Page.FindControl will only work with controls that are immediate children of the root element on the page. Instead, you should try calling FindControl recursively. You should also make sure that a control with the id TextQ1 exists - look in the HTML source for the page on the client to make sure a TextBox with this id exists.
There are many examples of this on the net. Here's a VB.Net version (source: http://www.pavey.me/2007/09/recursive-pagefindcontrol-for-vbnet.html) that you can add to your page:
Public Function FindControlRecursive(Of ItemType)(ByVal Ctrl As Object, ByVal id As String) As ItemType
If String.Compare(Ctrl.ID, id, StringComparison.OrdinalIgnoreCase) = 0 AndAlso TypeOf Ctrl Is ItemType Then
Return CType(Ctrl, ItemType)
End If
For Each c As Control In Ctrl.Controls
Dim t As ItemType = FindControlRecursive(Of ItemType)(c, id)
If t IsNot Nothing Then
Return t
End If
Next
Return Nothing
End Function
Your line in the code above would then become:
oTextBox = FindControlRecursive(of TextBox)(Page.Controls(0), "TextQ" & CStr(check))
You'd also need to do the same for the Label control.
It Look like you are using only name istead of textbox try with the code below
Private Sub GoGoGo()
Dim Textboxname As String '
Dim textbox As TextBox
Dim TextboxText As Object
Dim Labelname As String
Dim label As Object
Dim LabelText As Object
Dim Number As Integer = 1
Dim MaxTime As Integer = 9
Dim Currentloop As Integer = 1
For check As Integer = Currentloop To MaxTime
If Currentloop <= MaxTime Then
Textboxname = "TextQ" + Number
textbox = Ctype(Me.Controls(Textboxname), TextBox)
TextboxText = textbox.Text
textbox.ReadOnly = True
End If
If Currentloop <= MaxTime Then
Labelname = "Label" + Number
label = Labelname
LabelText = label.Text
label.Visible = True
End If
Number = Number + 1
If TextboxText = "" Then
label.Text = "no imput"
label.ForeColor = Drawing.Color.Black
End If
If TextboxText = "server" Then
label.Text = "Correct"
label.ForeColor = Drawing.Color.Green
End If
If TextboxText = "Wrong" Then
label.Text = "Wrong"
label.ForeColor = Drawing.Color.Red
End If
If check = 9 Then
Exit For
End If
Next
End Sub

Resources