adding editable CheckBoxField to gridview - asp.net

I am trying programatically add a check box column to a grid view. This grid view has multiple other columns but I only want the check box column to be editable. The only examples I have seen require that I add an "Edit" link to each row. I would like for the check box column to be editable by default, without the need for a link. The check box should also support autopost backs. Anyone have any suggestions? Below is what I have so far:
Dim gv As New GridView
With gv
.ID = "gridViewFoundUsers"
.AutoGenerateColumns = False
.DataKeyNames = New String() {"UserId"}
.GridLines = GridLines.Both
.AllowSorting = True
.AllowPaging = True
.PageSize = numRows
.Width = tableWidth
.BorderColor = Drawing.ColorTranslator.FromHtml("#808080")
.AutoGenerateEditButton = True
.HeaderStyle.CssClass = foundUserHeadStyle
.RowStyle.CssClass = foundUserEvenRows
.Columns.Clear()
Dim UserIdTF As New BoundField
With UserIdTF
.DataField = "UserId"
.HeaderText = "UserID"
.SortExpression = "UserId"
.ItemStyle.Wrap = True
.ItemStyle.Width = 100
End With
Dim DomainTF As New BoundField
With DomainTF
.HeaderText = "Domain"
.DataField = "Domain"
.SortExpression = "Domain"
.ItemStyle.Wrap = False
.HeaderStyle.Font.Underline = False
End With
Dim SelectUserTF As New CheckBoxField
With SelectUserTF
.HeaderText = "Select User"
.ItemStyle.Wrap = False
.DataField = "isSelected"
End With
.Columns.Add(UserIdTF)
.Columns.Add(DomainTF)
.Columns.Add(SelectUserTF)
End With
The gridview is part of a composite server control, so there is no client side code pages.
Thanks!

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

Add Two Controls in a Table Cell not working

Hi I am trying to add two controls into a table cell the code is below. Unfortunately the hyperlink is always outside the table cell, whilst the label is inside. Individually they are working fine but together not so good, could somebody help me please.
Dim iCell As New TableCell
Dim lbl As New Label
lbl.Height = Unit.Pixel(100)
lbl.Width = Unit.Pixel(150)
lbl.Style.Add("padding", "5px")
lbl.Style.Add("border-radius", "10px")
lbl.BorderStyle = BorderStyle.Solid
lbl.BorderWidth = Unit.Pixel(1)
lbl.BorderColor = Color.Black
lbl.Font.Size = 9
lbl.Text = "Event: " & dt.Rows(y).Item("eventname")
lbl.BackColor = ColorTranslator.FromHtml(dt.Rows(y).Item("roomcolor"))
Dim hyp As New HyperLink
hyp.Font.Size = 9
hyp.Text = "Modify"
hyp.NavigateUrl = "modify.aspx"
iCell.Controls.Add(lbl)
iCell.Controls.Add(hyp)
iCell.VerticalAlign = VerticalAlign.Top
tRow.Cells.Add(iCell)

adding a chart control to a placeholder ASP.net VB

I'm trying to add a manually created chart to a placeholder but when i look at the output all i get is a blank.. I am getting the data from a dataset datatable that is the last table in the dataset. I only has two colums "Industry" and "industryTheta" any help is much appreciated. I'm not sure whats wrong here
Dim chrt As New Chart
chrt.ID = "dynChart"
chrt.Height = Unit.Pixel(1000)
chrt.Width = Unit.Pixel(1000)
chrt.BackImageWrapMode = ChartImageWrapMode.Scaled
chrt.BorderlineColor = Color.Black
chrt.ImageLocation = "~/TempImages/ChartPic_#SEQ(300,3)"
chrt.BackGradientStyle = GradientStyle.None
Dim ca As New ChartArea
ca.Name = "IndustryTheta"
ca.AlignmentOrientation = AreaAlignmentOrientations.All
ca.AlignmentStyle = AreaAlignmentStyles.All
ca.Area3DStyle.Enable3D = True
ca.Area3DStyle.LightStyle = LightStyle.Realistic
ca.Area3DStyle.Inclination = 30
ca.BackHatchStyle = ChartHatchStyle.None
chrt.ChartAreas.Add(ca)
Dim sers As New Series
sers.Name = "IndustryName"
sers.ChartType = SeriesChartType.Pie
sers.Label = "#VALX, #PERCENT"
sers.LabelAngle = 90
sers.IsXValueIndexed = True
sers.IsValueShownAsLabel = True
sers.XAxisType = AxisType.Primary
sers.YAxisType = AxisType.Primary
sers.YValuesPerPoint = 1
sers.XValueMember = "Industry"
sers.YValueMembers = "IndustryTheta"
chrt.Series.Add(sers)
For Each dr As DataRow In table.Rows
Dim p As New DataPoint
p.SetValueY(Convert.ToInt32(dr.Item("IndustryTheta")))
p.AxisLabel = dr.Item("Industry")
sers.Points.Add(p)
Next
chrt.DataBind()
dynamicGrids.Controls.Add(chrt)
Most likely your problem is with when you are calling your function in the page life cycle. Please refer to this information to learn more about it.
In order to address dynamic controls in asp.net please refer to this for more information on dynamic controls.

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

asp.net vb.net gridview - can't sort!

I try to make this gridview sortable, but it simply doesn't work, anyone know why?
Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
sql = sql & "FROM Product "
sql = sql & "WHERE Category = ? "
Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim dad As New OleDbDataAdapter(sql, conn)
dad.SelectCommand.Parameters.AddWithValue("?", CatID)
Dim dtblProduct As New DataTable()
dad.Fill(dtblProduct)
Dim grdProducts As New GridView
grdProducts.ID = "grdProducts"
grdProducts.CellPadding = 5
grdProducts.CellSpacing = 5
grdProducts.GridLines = GridLines.None
grdProducts.AutoGenerateColumns = False
grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
grdProducts.EmptyDataText = "No Products Available."
grdProducts.DataSource = dtblProduct
Dim dataNavigateUrlFields() As String = {"Product_ID"}
Dim blnfirstCol As Boolean = True
Dim strPageResolveURL As String = String.Empty
Dim strLnkSelectText As String = String.Empty
For Each col As Data.DataColumn In dtblProduct.Columns
If blnfirstCol Then
Dim lnkSelect As New HyperLinkField
With lnkSelect
.Text = _strAction
.DataNavigateUrlFields = dataNavigateUrlFields
.DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
End With
grdProducts.Columns.Add(lnkSelect)
blnfirstCol = False
Else
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case "CODE"
.HeaderText = "Code"
.ItemStyle.Width = 100
.HtmlEncode = False
Case "TRADE_NAME"
.HeaderText = "Trade Name"
.ItemStyle.Width = 200
End Select
.DataField = col.ColumnName
.Visible = True
End With
grdProducts.Columns.Add(myBoundField)
End If
Next
grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
grdProducts.DataBind()
It's frustrating!
I think you are not assigning SortExpression property in Columns.
Please check this example for more detail.
In your example, just add
.SortExpression= col.ColumnName
below
.DataField = col.ColumnName
Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.

Resources