Dynamically Create Controls Based On Database field Asp.net - asp.net

I have a database table that looks like so:
fieldid
form_id
control_type
parentid
order_number
1
1
panel
0
0
2
1
textbox
0
1
3
1
checkbox
0
0
4
1
panel
1
0
1
1
checkbox
4
0
1
1
textbox
4
1
There are other fields that I want to attach to this table but I want to dynamically create controls within the associated panel by using recursion.
I call the load_form with two parameters from the page_load event
my page has one panel in it called PnlMain and this panel is where I want the dynamically loaded controls placed within.
can anyone help me out with how to load only the controls that are associated with the "panels" with the fieldid that's equal to the associated controls parentid
Here is my code behind.
Sub load_form(c As Control, Optional parent_id As Integer = 0)
i = i + 1
Dim frmid As Integer
If Request("formid") Is Nothing Then
frmid = 1
Else
frmid = Request("formid")
End If
Dim dt As DataTable
Dim sql As String = ""
If parent_id = 0 Then
sql = "SELECT * from form_fields where form_id=" & frmid & " order by parentid, order_number"
dt = GetData(sql)
Else
sql = "SELECT * from form_fields where form_id=" & frmid & " and parentid=" & parent_id & " order by parentid, order_number"
dt = GetData(sql)
End If
If dt.Rows.Count > 0 Then
For Each row As DataRow In dt.Rows
' MsgBox(sql)
Dim p As New Panel()
If row(2).ToString.Trim(" ") = "panel" Then
' MsgBox(dt.Rows(0)(0))
Dim pnl As New Panel()
pnl.ID = "pnl" & row(0)
pnl.GroupingText = row(9)
p = pnl
load_form(p, row(0))
End If
If row(2).ToString.Trim() = "textbox" Then
Dim t As New TextBox With {
.CssClass = "form-control"}
t.Attributes.Add("showto", "true")
t.Attributes.Add("dbdata", "true")
t.Attributes.Add("placeholder", "Enter O2 Level...")
t.ID = "Txt" & i
p.Controls.Add(t)
End If
If row(2).ToString.Trim() = "checkbox" Then
Dim cb As New CheckBox With {
.CssClass = "cb form-control"}
cb.Attributes.Add("showto", "All")
cb.Attributes.Add("dbdata", "true")
cb.Attributes.Add("title", row("title").ToString.Trim())
cb.Attributes.Add("altValue", row("altvalue").ToString.Trim())
cb.Text = row(7).ToString.Trim()
cb.ID = "cb" & i
p.Controls.Add(cb)
End If
c.Controls.Add(p)
Next
End If
End Sub

Related

Retrieving values from dynamically created controls

First post, so go easy on me.
I've been coding for years, first with VB6, then VB.NET and more recently ASP.NET. I'm ashamed to say, this issue has beaten me to the point where I need to ask for help. What's more annoying is that this should be a simple thing to achieve! I'm clearly missing something here.
I'm creating checkbox controls dynamically, quite a few of them in fact. Two per dynamically created table row and their IDs are appended with the ID of the particular DB record on the row, row 1, 2, 3 etc. So on each row there would be two checkboxes, ihave_check_1, ineed_check_1. The next row would be ihave_check_2 and ineed_check_2 and so on.
There is a submit button at the bottom of the page, and when clicked, it's supposed to loop through each row (and cell) in the table and pick out controls whose IDs contain "ihave_check_" and "ineed_check_" then get their Checked value. Once I have the values, I add a record into the database.
Problem is, when you click the button, the table disappears and so do the values.
From what I've read so far, this is happening because the controls are dynamically created, if they were static (coded in the HTML section) I wouldn't have this problem.
So first question, what do I need to do to get it working?
And second question, why is using dynamic controls so difficult?
Here's the code setting up the table, which works great:
Private Sub ddCardSeries_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddCardSeries.SelectedIndexChanged
If IsPostBack = True And Not ddCardSeries.SelectedValue = "Select..." Then
cardsTable.Visible = True
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXXXXX;")
Dim dtSections As New DataTable
dtSections = dat.DataSelect("SELECT baseCardID,baseCardSeries,baseCardNumber,baseCardName,frontArtist,conceptArtist,backArtist,backWriter,isBaseCard,isDieCut,isMatte,isGlossy,differentBack,frontImage,backImage FROM baseCards where baseCardSeries = '" & Split(Split(ddCardSeries.Text, "(ID:")(1), ")")(0) & "' and isBaseCard = 'Yes'")
If dtSections.Rows.Count > 0 Then
For i As Integer = 0 To dtSections.Rows.Count - 1
Dim row As New TableRow
For x = 0 To dtSections.Columns.Count - 1
Dim cell1 As New TableCell
If Not IsDBNull(dtSections.Rows(i)(x)) Then
If x = 0 Then
cell1.Text = dtSections.Rows(i)(x)
ElseIf x = 1 Then
cell1.Text = get_card_series(dtSections.Rows(i)(x))
ElseIf x = 13 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
ElseIf x = 14 Then
cell1.Text = "<img src='" & dtSections.Rows(i)(x) & "' height='120'"
Else
cell1.Text = dtSections.Rows(i)(x)
End If
Else
cell1.Text = ""
End If
row.Cells.Add(cell1)
Next x
Dim newbutton As New Button
Dim newlabel As New Label
newlabel.Text = "<br />"
newbutton.Text = "Modify this entry"
newbutton.Width = 120
newbutton.ID = "modify_button_" & dtSections.Rows(i)(0)
Dim newcheck1 As New CheckBox
Dim newlabel2 As New Label
newlabel2.Text = "<br />"
newcheck1.Text = "I own this card"
newcheck1.Width = 120
newcheck1.ID = "ihave_check_" & dtSections.Rows(i)(0)
Dim newcheck2 As New CheckBox
newcheck2.Text = "I need this card"
newcheck2.Width = 120
newcheck2.ID = "ineed_check_" & dtSections.Rows(i)(0)
Dim cell2 As New TableCell
If is_user_admin() = True Then
newbutton.Enabled = True
Else
newbutton.Enabled = False
End If
cell2.Controls.Add(newbutton)
cell2.Controls.Add(newlabel)
cell2.Controls.Add(newcheck1)
cell2.Controls.Add(newlabel2)
cell2.Controls.Add(newcheck2)
row.Cells.Add(cell2)
cardsTable.Rows.Add(row)
Next
End If
Else
cardsTable.Visible = False
End If
End Sub
Here's the code that loops through the table and tries to save the results to the database:
Protected Sub SubmitChanges_Click(sender As Object, e As EventArgs) Handles SubmitChanges.Click
For Each pcontrol As control In Page.Controls
Dim havecard As String = Nothing
Dim needcard As String = Nothing
Dim rowcardid As String = Nothing
'For Each tabcell As TableCell In tabrow.Cells
'For Each pgcontrol As Control In tabcell.Controls
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ihave" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
havecard = "Yes"
Else
havecard = "No"
End If
End If
If TypeOf pcontrol Is CheckBox And Split(pcontrol.ID, "_")(0) = "ineed" Then
rowcardid = Split(pcontrol.ID, "_")(2)
Dim chkbox As CheckBox = pcontrol
If chkbox.Checked = True Then
needcard = "Yes"
Else
needcard = "No"
End If
End If
'Next
If Not havecard = Nothing And Not needcard = Nothing Then
If add_card_to_user_list(Session("username"), rowcardid, havecard, needcard) = True Then
Label1.Text = "Update complete"
Else
Label1.Text = "Update failed"
End If
End If
'Next
Next
End Sub
Public Function add_card_to_user_list(ByVal userid As String, ByVal cardid As String, ByVal own As String, ByVal need As String) As Boolean
Try
Dim dat As New DataLayer3.DataConnector
dat.DataConnector("Provider=SQLOLEDB;Server=192.XXX.XXX.XXX;Database=GPKDB;User Id=sa;Password=XXXXXXXX;")
Dim dtCardSeries As New DataTable
dtCardSeries = dat.DataSelect("select CardID from [" & userid & "_cards] where cardid = '" & cardid & "'")
If dtCardSeries.Rows.Count > 0 Then
dat.DataDelete("delete from [" & userid & "_cards] where cardid = '" & cardid & "'")
End If
dat.DataInsert("insert into [" & userid & "_cards] (Username,CardID,Own,Need) values ('" & userid & "', '" & cardid & "', '" & own & "', '" & need & "');")
Return True
Catch ex As Exception
Return False
End Try
End Function
Any help at this point would be gratefully received.
Thanks!

Can't find dynamically created TD in code behind

I have created a dynamic table in my code behind which loads up on page load. I have created a button which when clicked I need to add a <div> to specific <td> in the table. However, it is not finding my <td> element using the id. What am I doing wrong?
Function CalendarRefresh(Day As Integer, MonthDays As Integer)
Dim iDay As Integer = 1
Dim TableID As Integer
Dim TDCount As Integer = 0
Dim FullTDCount As Integer = 0 '42
Dim StringHtml As New StringBuilder
Dim DaysInMonth As Integer = MonthDays
clsWork.GetUnscheduledWork()
Dim ClientName = "Terence Creighton" ' Test Replace with DB Value
Dim JobName = "Install Job"
' Top structure of table
StringHtml.Append("<table id='calendar' runatserver='server'>")
StringHtml.Append("<tr class='weekdays'>")
StringHtml.Append("<th scope='col'>Sunday</th>")
StringHtml.Append("<th scope='col'>Monday</th>")
StringHtml.Append("<th scope='col'>Tuesday</th>")
StringHtml.Append("<th scope='col'>Wednesday</th>")
StringHtml.Append("<th scope='col'>Thursday</th>")
StringHtml.Append("<th scope='col'>Friday</th>")
StringHtml.Append("<th scope='col'>Saturday</th>")
StringHtml.Append("</tr>")
StringHtml.Append("<tr Class='days'>")
If Day > 1 Then
Do While iDay < (Day)
' add Previous month style
StringHtml.Append("<td class='day other-month'>")
StringHtml.Append("</td>")
iDay = iDay + 1
TDCount = TDCount + 1
FullTDCount = FullTDCount + 1
Loop
End If
For i As Integer = 1 To DaysInMonth
If TDCount = 7 Then
StringHtml.Append("</tr>")
StringHtml.Append("<tr class='days'>")
TDCount = 0
FullTDCount = FullTDCount + 1
i = i - 1
Else
StringHtml.Append("<td class='day' ")
StringHtml.Append("id='")
StringHtml.Append(i)
StringHtml.Append("' Runat='server'>")
StringHtml.Append("<div class='date'>")
StringHtml.Append(i)
StringHtml.Append("</div>")
'StringHtml.Append("<div id='")
'StringHtml.Append(i)
'StringHtml.Append("' Runat='server'>")
'StringHtml.Append("<div Class='panel panel-primary' draggable='true'>")
'StringHtml.Append("<div Class='panel-heading'>")
'StringHtml.Append(ClientName)
'StringHtml.Append("</div>")
'StringHtml.Append("<div Class='panel-body'>")
'StringHtml.Append(JobName)
'StringHtml.Append("</div>")
'StringHtml.Append("</div>")
StringHtml.Append("</div>")
StringHtml.Append("</td>")
TDCount = TDCount + 1
FullTDCount = FullTDCount + 1
End If
Next
StringHtml.Append("</tr>")
StringHtml.Append("</table>")
Return StringHtml.ToString
End Function
Public Sub ScheduledJobs()
Dim StringHtml As New StringBuilder
Dim ClientName As String
Dim JobName As String
Dim Work = clsWork.GetUnscheduledWork()
For Each i As Integer In Work.Rows.Count
ClientName = Work.Rows(i).Items("ClientName").ToString
JobName = Work.Rows(i).Items("JobName").ToString
ID = i.ToString
StringHtml.Append("<div class='panel panel-primary' draggable='true' ondragstart='OnDragStart' ondrop='OnDrop' ")
StringHtml.Append("id='")
StringHtml.Append(ID)
StringHtml.Append("'>")
StringHtml.Append("<div class='panel-heading'>")
StringHtml.Append(ClientName)
StringHtml.Append("</div>")
StringHtml.Append("<div class='panel-body'>")
StringHtml.Append(JobName)
StringHtml.Append("</div>")
Next
Dim MyTable As HtmlTable = Page.FindControl("calendar")
Dim MyCell As HtmlTableCell
MyCell.ID = "19"
If MyCell Is Nothing Then
messageResponse = "Tablecell not found"
Else
MyCell.InnerHtml = StringHtml.ToString
End If
End Sub
Private Sub cmdLoadJobs_ServerClick(sender As Object, e As EventArgs) Handles cmdTry.ServerClick
ScheduledJobs()
End Sub
I am expecting find the td with the ID and add the html string in the ("td Element").innerhtml. I have tried various combinations of findcontrol but all turns up empty
You have to create real dynamic controls. Here a very basic example of how to interact with a dynamically created table.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//do not create dynamic control in an ispostback check
}
//create some table and it's rows and cells. note the assignent of an ID
Table table = new Table()
{
ID = "MyTable1"
};
TableRow row = new TableRow()
{
ID = "MyRow1"
};
TableCell cell = new TableCell()
{
ID = "MyCell1",
Text = "My 1st cell"
};
//add the cell to the row
row.Controls.Add(cell);
//add the row to the table
table.Controls.Add(row);
//add the table to the page
PlaceHolder1.Controls.Add(table);
}
protected void Button1_Click(object sender, EventArgs e)
{
//use findcontrol to locate the cell
TableCell cell = PlaceHolder1.FindControl("MyCell1") as TableCell;
//interact with it
cell.Text = "Cell Found!";
}
I see this:
StringHtml.Append("<table id='calendar' runatserver='server'>")
While it's certainly fine to push raw html to a page in the browser by building an html string, you cannot create server controls this way. You won't be able to access anything in that html from your code behind. The runat='server' part is first of all keyed wrong, but would be worthless even if written correctly. By the time you're in the Page_Load event, everything that looks for the runat='server' attribute has already finished.

How to insert a new row between another rows in gridview boundfield?

I have a gridview like below picture:
In this gridview I want to introduce a new row that does not have any completely out of the cell where the last "Grand Total" there to put a variable mine.
But the question is, how introduce a new row among others?
My code is:
Dim Qty As Double = 0
Dim CostCategory As Double = 0
Dim AssemblyDate As String = Nothing
If GridView1.Rows.Count <> 0 Then
For x As Integer = 0 To GridView1.Rows.Count - 1
For y As Integer = 0 To GridView1.Columns.Count - 1
If y = 0 And GridView1.Rows(x).Cells(1).Text = AssemblyDate Then
GridView1.Rows(x).Cells(1).Text = ""
End If
If GridView1.Rows(x).Cells(1).Text <> Nothing Then
AssemblyDate = GridView1.Rows(x).Cells(1).Text
End If
If y = "9" Then
Qty = Convert.ToDouble(GridView1.Rows(x).Cells(9).Text)
End If
If y = "13" Then
CostCategory = Convert.ToDouble(GridView1.Rows(x).Cells(13).Text)
End If
If y = "14" Then
GridView1.Rows(x).Cells(14).Text = Qty * CostCategory
GridView1.Rows(x).Cells(14).HorizontalAlign = HorizontalAlign.Center
End If
If GridView1.Rows(x).Cells(y).Text = "Yes" Then
GridView1.Rows(x).Cells(y).BackColor = System.Drawing.Color.LawnGreen
ElseIf GridView1.Rows(x).Cells(y).Text = "No" Then
GridView1.Rows(x).Cells(y).BackColor = System.Drawing.Color.Red
End If
Next
Next
End if
before that code i have a query where i fill my gridview:
Dim myQuery As String = SelectQuery & WhereQuery
SqlDataSource1.SelectCommand = myQuery
SqlDataSource1.DataBind()
GridView1.DataSourceID = "SqlDataSource1"
GridView1.DataBind()
Thanks a lot!
Try using this
DataRow dr = tblTable.NewRow(); //Create New Row
dr["ColumnName"] = "Legs"; // Set Column Value
tblTable.Rows.InsertAt(dr, 11); // InsertAt specified position
For VB.Net Grid View
Dim rowNumber As Integer = dGrid.CurrentCell.RowNumber() + 1
Dim myNewRow As DataRow = myDataTable.NewRow()
myDataTable.Rows.InsertAt(myNewRow, rowNumber)
myDataTable.AcceptChanges()

Adding Rows dynamically to GridView in ASP.NET

I use the following code for adding Rows dynamically to GridView in ASP.NET.
ViewState("CourseFeesDetails") = dsGetStudentCourseFeesDetail
If ViewState("CourseFeesDetails") IsNot Nothing Then
Dim dtCourseTable As New DataTable
dtCourseTable = CType(ViewState("CourseFeesDetails"), DataTable)
Dim drCurrentRow As DataRow = Nothing
Dim txtFeesAmt As New System.Web.UI.WebControls.TextBox
If dtCourseTable.Rows.Count > 0 Then
For i = 1 To nNoOfInstallments
drCurrentRow = dtCourseTable.NewRow()
i = i + 1
dtCourseTable.Rows.Add(drCurrentRow)
Next
ViewState("CourseFeesDetails") = dtCourseTable
gvCourseFeeDisplay.DataSource = dtCourseTable
gvCourseFeeDisplay.DataBind()
End If
End If
It does add the number of rows, but adds 1 extra. What should I do?

Error Cannot have multiple items selected in a DropDownList

This is my code and i am getting an error ..Cannot have multiple items selected in a DropDownList. when the page loads it select "ALL" in DDLModality but when i change DDLModality.selectedvalue to any "value" then no error but again when i change to "ALL "getting the error.
onchange of DDLMODALITY submit the form
form1.target = "";
form1.action = "";
form1.submit();
' USED TO ADD REFERRING PHYSICIAN IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '')"
Else
sql = "Select Ref_Phy_ID,Name from Ref_Phy_Master WHERE Ref_Phy_ID in(Select distinct Ref_Phy_ID from Patient_Details where Ref_Phy_ID <> '') And Center_ID = " & Session("CenterID")
End If
objDS = objFun.RunQuery(sql)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
cboRefPhy.Items.Add(Li1)
' USED TO COUNT THE STUDIES IN THE DROPDOWN
If (objDS.Tables(0).Rows.Count <> 0) Then
' USED TO CIRCULATE LOOP UPTO THE RECORD COUNT
Dim i As Integer
For i = 0 To objDS.Tables(0).Rows.Count - 1
' USED TO CREATE NEW ITEM IN THE DROPDOWN
Dim Li As New ListItem
Li.Text = objDS.Tables(0).Rows(i)("Name").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Ref_Phy_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
cboRefPhy.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
cboRefPhy.ClearSelection()
cboRefPhy.SelectedValue = Convert.ToString(Request.Form("cboRefPhy"))
'USED TO ADD MODALITY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Modality_ID,Modality from Hospital_Modality_Master WHERE Modality_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
'Dim objDS As New DataSet()
objDS = objFun.RunQuery(sqlStudy)
' USED TO REFRESH THE PAGE WHIN IT IS POSTED BACK
' USED TO DISPLAY DEFAULT FIRST ITEM IN THE DROPDOWN
'Dim Li1 As New ListItem()
Li1.Text = "ALL"
Li1.Value = ""
' Dim all As String
' all = "All"
'Ddl_Modality.Items.Add(all)
DDLModality.Items.Add(Li1)
' USED TO COUNT THE STUDIES IN THE DROPDOWN
If (objDS.Tables(0).Rows.Count <> 0) Then
' USED TO CIRCULATE LOOP UPTO THE RECORD COUNT
Dim i As Integer
For i = 0 To objDS.Tables(0).Rows.Count - 1
' USED TO CREATE NEW ITEM IN THE DROPDOWN
Dim Li As New ListItem
Li.Text = objDS.Tables(0).Rows(i)("Modality").ToString()
Li.Value = objDS.Tables(0).Rows(i)("Modality_ID").ToString()
'USED TO ADD ITEMS IN THE DROPDOWN
DDLModality.Items.Add(Li)
Next
End If
'USED TO SAVE THE CHANGES IN DATASET
objDS.AcceptChanges()
' USED TO CLOSE THE DATABASE CONNECTION
objDS.Dispose()
DDLModality.ClearSelection()
DDLModality.SelectedValue = Convert.ToString(Request.Form("DDLModality"))
' USED TO ADD STUDY IN THE DROPDOWN DYNAMICALLY
If CInt(Session("CenterID")) = 0 Then
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '')"
Else
sqlStudy = "Select Study_ID,Study_Desc from Study_Master WHERE Study_ID in(Select distinct Study_ID from Patient_Details where Study_ID <> '') And Center_ID = " & Session("CenterID")
End If
If (DDLModality.SelectedItem.Text <> "ALL") Then
sqlStudy = sqlStudy & " AND Modality = '" & DDLModality.SelectedItem.Text & "'"
End If
try
DDLModality.ClearSelection()
before setting DDLModality.SelectedValue
Dim Li2 As New ListItem()
Li2.Text = "ALL"
Li2.Value = ""
DDLModality.Items.Add(Li2)
I was facing the same problem. If you add one defined ListItem (in this case Li1) to two or more dropdownlists, this error will occur while assigning selectedvalue to any dropdownlist.
Simple solution is define separate ListItems for separate dropdownlists like Li1, Li2, Li3, etc.
Don't understand the logic behind, but it works!

Resources