ProblemwithfindTextBoxinASP.net - asp.net

i have the problem, that i create a TextBox via vb.net Code while the programm ist running.
Private Sub GenerateTBSourcePath()
'Generiert eine neue leere Textbox
Dim tBox As System.Web.UI.WebControls.TextBox = New System.Web.UI.WebControls.TextBox()
tBox.Width = 400
Dim tbID As Integer = tbSourcePathID + 1
tBox.ID = "tbSourcePath_" + tbID.ToString()
pSourcePath.Controls.Add(tBox)
End Sub
When i try to search for the TextBox on pSourcePath i cant find any TextBox.
Have anyone an idea what do i wrong?
i add the TextBox in start of my programm. I can see the TextBox also in the Browser. When i want to save the Text i cant find the TextBox.
Private Sub SaveTBox()
'Für jede TBox den Eintrag in der DB aktualisieren oder einen neuen Eintrag anlegen
For Each PControl As System.Web.UI.Control In pSourcePath.Controls
Dim Controltype As String = PControl.GetType().FullName
Select Case Controltype
Case "System.Web.UI.WebControls.TextBox"
Dim tBox As WebControls.TextBox = CType(PControl, WebControls.TextBox)
If CheckExists(tBox.ID) = True
'Update
Administration_DataSource.UpdateCommand = "Update di_source set PATH = '" & tBox.Text & "' where TBID = '" & tBox.ID & "'"
Administration_DataSource.Update()
Else
'Insert
tbSourcePathID = tbSourcePathID + 1
Administration_DataSource.InsertCommand = "Insert Into di_source(ID, PATH, TBID) values('" & tbSourcePathID & "', '" & tBox.Text & "', '" & tBox.ID & "')"
Administration_DataSource.Insert()
End If
End Select
Next
End Sub

I tried this code
int tbSourcePathID = 0;
TextBox tBox = new TextBox();
PlaceHolder pSourcePath = new PlaceHolder();
tBox.Width = 400;
int tbID = tbSourcePathID + 1;
tBox.ID = "tbSourcePath_" + tbID.ToString();
pSourcePath.Controls.Add(tBox);
foreach (System.Web.UI.Control PControl in pSourcePath.Controls)
{
string Controltype = PControl.GetType().FullName;
switch (Controltype)
{
case "System.Web.UI.WebControls.TextBox":
bool here = true;
break;
}
}
and it works. Maybe the problem is in CheckExists(). Remember also the use of FindControl()

Related

Dynamically add Script to a Dynamically Created Div at Runtime vb.net aspx

I have created a web form with a Parent div container that contains child divs based on an SQL query. The number of children is based on the number of rows in the query result. I am hitting a snag though, and I think it's because I am programmatically adding a script as the divs are created. I know the script works because I tested it. It just isn't firing for the dynamically created divs.
Here is what the code looks like in the child div. It works, but not on dynamically created divs.
Sub ThumbView()
lbl_Status.Text = "ThumbView"
ListPanel.Visible = False
Dim MyTable As String = "[Estimate_Info4]"
Dim Sql As String = "SELECT* FROM [Estimate_Info4]"
Dim dbConnection = New SqlConnection(connString)
Dim dbCommand = New SqlCommand(Sql, dbConnection)
Dim data As New SqlDataAdapter(dbCommand)
Dim table As New DataTable(MyTable)
Dim rowIndex As Integer = 0
'//////////Open Database Connection////////////
dbConnection.Open()
data.Fill(table)
'//////////Loop through Data & Create Div for each Record //////////////
For Each row As DataRow In table.Rows
For i As Integer = 0 To (table.Rows.Count - 1)
Try
rowIndex = i
'/////////////////Control Delcarations/////////////////////
Dim NumberName As String = CStr(table.Rows(rowIndex)("EstNumber")) & " " & CStr(table.Rows(rowIndex)("JobName"))
Dim CleanName As String = RemoveWhitespace(NumberName)
Dim LBL_EstId As Label = New Label
Dim LBL_EstNumber As Label = New Label
Dim LBL_EstName As Label = New Label
Dim LBL_EstAddress1 As Label = New Label
Dim LBL_EstAddress2 As Label = New Label
Dim LineBreak As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak1 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak2 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak3 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak4 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak5 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim div As HtmlGenericControl = New HtmlGenericControl("div")
Dim divleft As HtmlGenericControl = New HtmlGenericControl("div")
Dim divright As HtmlGenericControl = New HtmlGenericControl("div")
Dim MyScript As HtmlGenericControl = New HtmlGenericControl("Script")
Dim MyIMG As ImageButton = New ImageButton
Dim MyIMG2 As ImageButton = New ImageButton
Dim RecID As Integer = (table.Rows(rowIndex)("Id"))
Dim RecID2 As String = CStr(table.Rows(rowIndex)("Id"))
'/////////////////Add 1st Child Div//////////////////
div.Attributes.Add("runat", " = server")
div.Style.Add("Class", "test")
div.Style.Add("width:", "637px")
div.Style.Add("height:", "228px")
div.Style.Add("aria-multiline", "True")
div.Style.Add("font-family", "verdana")
div.Style.Add("aria-multiline", "True")
div.Style.Add("word-break", "break-all")
div.Style.Add("word-wrap", "break-word")
div.Style.Add("Padding", "100x")
div.Style.Add("Border", "thick solid #666666")
div.Style.Add("margin-bottom", "10px")
div.Style.Add("margin-top", "10px")
div.Style.Add("margin-right", "10px")
div.Style.Add("margin-left", "10px")
div.Style.Add("display", "inline-grid")
Panel1.Style.Add("display", "inherit")
Panel1.Controls.Add(div)
'/////////////////Add 1st Child to First Child Div Float Left to house Image//////////////////
Dim StartString As String = "<script language=" & Chr(34) & "vb" & Chr(34) & "runat=" & Chr(34) & "server" & Chr(34) & ">" & Chr(10)
Dim EndString As String = "Sub ImageBttn" & RecID & "_Click(sender As Object, e As ImageClickEventArgs) Handles ImageBttn" & RecID & ".Click" & Chr(10) &
"Dim JobName As String = ImageBttn" & RecID & ".DescriptionUrl" & Chr(10) & "Dim JobID As String = ImageBttn" & RecID2 & ".CommandName" & Chr(10) &
"Response.Redirect(String.Format(" & Chr(34) & "~/476.aspx?JobName={0}&JobID={1}" & Chr(34) & ", JobName, JobID))" & Chr(10) & "End Sub" '& Chr(10) & "</script>"
' Dim inputString As String = EndString.Replace((Char)34),"").ToString()
'MsgBox(StartString & EndString)
Dim Q As String = Chr(34).ToString
Dim aString As String = Q & "~/476.aspx?JobName={0}&JobID={1}" & Q & ", JobName, JobID))"
Dim mymsg As String = "You Clicked" & NumberName
Dim folderPath As String = Server.MapPath("~/Files/VBScripts/")
Dim Mypath As String = folderPath & CleanName & ".vbs"
Try
'Check whether Directory (Folder) exists.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists Create it.
Directory.CreateDirectory(folderPath)
End If
'Save the File to the Directory (Folder).
'Dim Path As String = Server.MapPath("~/Files/VBScripts/")
Dim fs As FileStream = File.Create(Mypath)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(EndString)
fs.Write(info, 0, info.Length)
fs.Close()
Catch ex As Exception
MsgBox("Something has gone wrong..." & vbNewLine & ex.Message)
End Try
MyIMG.Style.Add("ID", CleanName)
MyIMG.Style.Add("Runat", "server")
MyIMG.Style.Add("OnClick", "ImageBttn" & RecID & "_Click")
MyIMG.Style.Add("DiscriptionUrl", NumberName)
MyIMG.Style.Add("CommandName", RecID2)
MyIMG.Style.Add("Class", "inner")
' /////////////// Create VBScript File and Add to Div////////////////
MyScript.Attributes.Add("script language", "vb")
MyScript.Attributes.Add("runat", "server")
MyScript.Attributes.Add("src", MyPath)
' src="
divleft.Attributes.Add("runat", " = server")
divleft.Style.Add("Class", "inner")
divleft.Style.Add("width: ", "186px")
divleft.Style.Add("height:", "228px")
divleft.Style.Add("aria-multiline", "True")
divleft.Style.Add("font-family", "verdana")
divleft.Style.Add("aria-multiline", "True")
divleft.Style.Add("Padding", "100x")
divleft.Style.Add("Border", "1px Gray")
divleft.Style.Add("Float", "Right")
divleft.Style.Add("display", "inline-Block")
divleft.Controls.Add(MyScript)
div.Controls.Add(divleft)
'/////////////////Add 2nd Child to First Child Div Float Right to house Labels//////////////////
divright.Attributes.Add("runat", " = server")
divright.Style.Add("Class", "inner")
divright.Style.Add("width:", "351px")
divright.Style.Add("height:", "228px")
divright.Style.Add("aria-multiline", "True")
divright.Style.Add("font-family", "verdana")
divright.Style.Add("aria-multiline", "True")
divright.Style.Add("Padding", "100x")
divright.Style.Add("Border", "1px Gray")
divright.Style.Add("Float", "Left")
divright.Style.Add("display", "inline")
div.Controls.Add(divright)
'/////////////////Add Controls to all of the Children//////////////////
MyIMG.Style.Add("ID", CleanName)
MyIMG.Style.Add("Runat", "server")
MyIMG.Style.Add("DiscriptionUrl", NumberName)
MyIMG.Style.Add("CommandName", RecID2)
MyIMG.Style.Add("Class", "inner")
MyIMG.Style.Add("OnClick", "ImageBttn" & RecID & "_Click")
divleft.Controls.Add(MyIMG)
MyIMG.ImageUrl = "~/Images/BLDG1.jpg"
LBL_EstNumber.Style.Add("runat", "server")
LBL_EstNumber.Style.Add("Height", "21px")
LBL_EstNumber.Style.Add("Width", "266px")
LBL_EstNumber.Style.Add("Font-Names", "Verdana")
LBL_EstNumber.Style.Add("Font-Size", "medium")
LBL_EstNumber.Style.Add("Font-Bold", "True")
LBL_EstNumber.Style.Add("ForeColor", "#666666")
LBL_EstNumber.Text = Chr(10) & " " & CStr(table.Rows(rowIndex)("EstNumber")) & " "
divright.Controls.Add(LineBreak1)
divright.Controls.Add(LBL_EstNumber)
LBL_EstNumber.Font.Bold = True
LBL_EstName.Style.Add("runat", "server")
LBL_EstName.Style.Add("Height", "21px")
LBL_EstName.Style.Add("Width", "266px")
LBL_EstName.Style.Add("Font-Names", "Verdana")
LBL_EstName.Style.Add("Font-Size", "medium")
LBL_EstName.Style.Add("Font-Bold", "True")
LBL_EstName.Style.Add("ForeColor", "#666666")
LBL_EstName.Text = Chr(10) & " " & CStr(table.Rows(rowIndex)("JobName")) & " "
divright.Controls.Add(LineBreak2)
divright.Controls.Add(LBL_EstName)
LBL_EstName.Font.Bold = True
LBL_EstAddress1.Style.Add("runat", "server")
LBL_EstAddress1.Style.Add("Height", "21px")
LBL_EstAddress1.Style.Add("Width", "266px")
LBL_EstAddress1.Style.Add("Font-Names", "Verdana")
LBL_EstAddress1.Style.Add("Font-Size", "Small")
LBL_EstAddress1.Style.Add("ForeColor", "666666")
LBL_EstAddress1.Text = CStr(table.Rows(rowIndex)("JobAddress"))
divright.Controls.Add(LineBreak3)
divright.Controls.Add(LBL_EstAddress1)
LBL_EstAddress2.Style.Add("runat", "server")
LBL_EstAddress2.Style.Add("Height", "21px")
LBL_EstAddress2.Style.Add("Width", "266px")
LBL_EstAddress2.Style.Add("Font-Names", "Verdana")
LBL_EstAddress2.Style.Add("Font-Size", "Small")
LBL_EstAddress2.Style.Add("ForeColor", "666666")
LBL_EstAddress2.Text = CStr(table.Rows(rowIndex)("JobCity")) & ", " & CStr(table.Rows(rowIndex)("JobState")) & " " & CStr(table.Rows(rowIndex)("JobZipCode"))
divright.Controls.Add(LBL_EstAddress2)
divright.Controls.Add(LineBreak4)
MyIMG2.Style.Add("runat", "server")
divright.Controls.Add(MyIMG2)
Dim EstStatus As Integer = (table.Rows(rowIndex)("EstimateStatus"))
If EstStatus = 2 Then MyIMG2.ImageUrl = "~/Images/Loss.jpg"
If EstStatus = 3 Then MyIMG2.ImageUrl = "~/Images/Awarded.jpg"
If EstStatus = 1 Then MyIMG2.ImageUrl = "~/Images/Pending.jpg"
Catch Ex As Exception
MsgBox("We've encountered an error; " & Ex.Message)
End Try
Next
Next
'/////////////////unhide the parent//////////////
Panel1.Style.Add("Height", "800px")
Panel1.Style.Add("width", "1800px")
Panel1.Style.Add("overflow", "scroll")
Panel1.Style.Add("overflow-y", "Scroll")
Panel1.Style.Add("overflow-x", "scroll")
Panel1.Visible = True
End Sub
'end result
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/Images/BLDG1.jpg" OnClientClick="ImageButton4_Click" DescriptionUrl="EST 02 Concrete Superstructure Hotel" EnableTheming="True" />
<script language="vb" runat="server">
Sub ImageButton4_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton4.Click
Dim JobName As String = ImageButton4.DescriptionUrl
Dim JobID As String = ImageButton4.CommandName
Response.Redirect(String.Format("~/476.aspx?JobName={0}&JobID={1}", JobName, JobID))
End Sub
</script>
I would not write all that code to inject repeating data into a web page. It not only too much code, but then after you done that, then trying to pluck out, or have the user operate against a given row of data is too much work.
I suggest you create ONE thing, lay it out correct in the desinger, and then simply feed it data.
So, say we have this:
So create the "one thing", lay it out nice. style it - do whatever. The result is simple, no code, use markup - you are done.
Now, look how easy it now becomes to "repeat" the data over and over with this code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' load the Repeater
LoadData
End If
End Sub
Sub LoadData()
Using cmdSQL As SqlCommand = New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Repeater1.DataSource = cmdSQL.ExecuteReader
Repeater1.DataBind()
End Using
End Sub
Output:
Now, was that not oh so easy? And then we can add css, get fancy, and improve that grid, but NOT have to touch the code behind!!!
And now, it becomes SUPER easy to deal with one thing. For example, we have that button click in the div. Lets get the row clicked, get the database PK id, and lets shove that into a label FOR THE ONE repeater item.
The code is thus this:
Protected Sub cmdTest_Click(sender As Object, e As EventArgs)
' btn click
Dim btn As Button = sender
Dim rRow As RepeaterItem = btn.Parent
Dim str As String = "Row Clicked = " & rRow.ItemIndex & " (PK ID = " & btn.Attributes.Item("PKID") & ")<br/>"
Dim txtHotel As TextBox = rRow.FindControl("txtHotel")
str &= "Hotel name = " & txtHotel.Text
' now setup label
Dim lbl As Label = rRow.FindControl("Label1")
lbl.Text = str
End Sub
I mean, how easy was that? So if we click on the 3nd one, we see this:
So, put your repeating stuff into of al things a "repeater".
Note how easy, how clean, how little code was written, and yet we get amazing ability here.
So, I recommend that you move out your code from the vb side, put it into a single nice layout, and then just shove data into that repeater - and it will "repeat" the data for you over and over.
Don't hard code all that markup in VB - it too much work, too hard, and costs too much time to get things done.
Edit:
So we use this code to load:
Sub LoadData()
Using cmdSQL As SqlCommand = New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim rst As New DataTable
rst.Load(cmdSQL.ExecuteReader)
Repeater1.DataSource = rst
Repeater1.DataBind()
End Using
End Sub
We used a datatable - since we need it later.
Now our row data bind event to change the status button is this:
Protected Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Select Case e.Item.ItemType.ToString
Case "Item", "AlternatingItem"
Dim btnImage As ImageButton = e.Item.FindControl("cmdStatus")
Select Case e.Item.DataItem("Status")
Case 1
btnImage.ImageUrl = "Content/ok.png"
Case 2
btnImage.ImageUrl = "Content/ckdelete.png"
Case 3
End Select
Case "Footer"
End Select
End Sub
our markup is this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="float:left;width:auto;border:solid;border-width:2px;padding:15px;margin-right:20px;border-radius:25px;box-shadow: 5px 5px #888888">
<div style="text-align:center">
<img src="Content/Skyline.PNG" />
<br />
<asp:Label ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>'></asp:Label>
<br />
<asp:Label ID="txtAD" runat="server" Text='<%# Eval("Address") %>'></asp:Label>
<br />
Active :<asp:CheckBox ID="Active" runat="server" Checked ='<%# Eval("Active") %>'></asp:CheckBox>
<asp:Button ID="cmdTest" runat="server" Text="Row Click" OnClick="cmdTest_Click"
PKID = '<%# Eval("ID") %>'
/>
<br />
<div style="float:left">
<asp:ImageButton ID="cmdStatus" runat="server" ImageUrl="Content/ok.png" Height="20px" Width="20px"/>
</div>
</div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
Output:
The beauty of above? We can now click on that button, or even the lower left check box - and we now have a simple event button code behind to grab that row - we can now show or launch another page based on clicking on each item.
Note how it took me less then 5 minutes to change my layout - that's because I am NOT writing code to do that layout and the mark-up part. So it was super easy for me to change the layout - even adding the graphic image.
OK, I'm going another route and the code is not firing.
I know there are easier ways to do this- So I'm adding a photo of webapps thumb view-there is also a list view view with icons indicating status. All I need now is the code to fire-It shows up on the page when I inspect.
![webform view]: (https://1drv.ms/u/s!AmmK5IyEVLSlg9gQSd_eb5KzA8UVcg?e=8sSdvI)
` Try
Dim csName As [String] = "ClientScript" & RecID
Dim csType As Type = divleft.[GetType]()
Dim cs As ClientScriptManager = Page.ClientScript
If Not cs.IsClientScriptBlockRegistered(csType, csName) Then
Dim csText As New StringBuilder()
csText.Append("<script language=" & Chr(34) & "vb" & Chr(34) & "runat=" & Chr(34) & "server" & Chr(34) & ">")
csText.Append("Sub ImageBttn" & RecID & "_Click(sender As Object, e As ImageClickEventArgs) Handles ImageBttn" & RecID & ".Click" & Chr(10) &
"Dim JobName As String = ImageBttn" & RecID & ".DescriptionUrl" & Chr(10) & "Dim JobID As String = ImageBttn" & RecID2 & ".CommandName" & Chr(10) &
"Response.Redirect(String.Format(" & Chr(34) & "~/476.aspx?JobName={0}&JobID={1}" & Chr(34) & ", JobName, JobID))" & Chr(10) &
"msgbox(ImageBttn" & RecID & ".DescriptionUrl)" & Chr(10) & "End Sub" & Chr(10) & "</script>")
cs.RegisterClientScriptBlock(csType, csName, csText.ToString())
End If
Catch ex As Exception
MsgBox("Something has gone wrong..." & vbNewLine & ex.Message)
End Try``

after logout from users account all page shows error

I have vb.net web application in which if users are logged in than all other pages working fine but the time I log out from account than it gets error in all pages. I know the page getting values from cookies but if cookies is empty then it's getting null & so cause the error page
Error : System.NullReferenceException: Object reference not set to an instance of an object.
VB Code for any pageload
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Dim LogIn, LogOut, listup As Control
Dim BtnProfile As Button = Page.Master.FindControl("myAccount")
LogIn = Master.FindControl("login")
LogOut = Master.FindControl("logout")
listup = Master.FindControl("list")
'not login
If HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
listup.Visible = True
LogIn.Visible = True
LogOut.Visible = False
BtnProfile.Visible = False
'login
Else
LogOut.Visible = True
BtnProfile.Visible = True
LogIn.Visible = False
listup.Visible = False
End If
Login Page code
Dim User, Pass As String
If selectbusinesstype.SelectedValue.ToString = "0" Then
Response.Write("<script language='javascript'>alert('Select login type first');</script>")
ElseIf selectbusinesstype.SelectedValue = "Hospitals" Then
Try
If loginId.Text <> "" And password.Text <> "" Then
Dim str As String = "select * from hospitals where username='" + loginId.Text + "' and Password='" + password.Text + "';"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
con.Close()
User = ds.Tables(0).Rows(0)("username")
Pass = ds.Tables(0).Rows(0)("password")
If ds.Tables(0).Rows.Count > 0 Then
If User = loginId.Text.ToString And Pass = password.Text.ToString Then
Response.Cookies("User_Type").Value = "Hospitals"
Response.Cookies("chkusername").Value = loginId.Text
Response.Redirect("hospital-profile.aspx?user=" + Request.Cookies("chkusername").Value)
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('User name or password is invalid');</script>")
End If
Else
Response.Write("<script language='javascript'>alert('Enter All the Details');</script>")
End If
Catch ex As Exception
Response.Write("<br /><br /><br /><br /><br />")
Response.Write(ex)
con.Close()
End Try
You have below lines,
Dim var, Type As String
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
Convert it to,
Dim var, Type As String
If not HttpContext.Current.Request.Cookies("chkusername") Is Nothing Then
var = Server.HtmlEncode(Request.Cookies("chkusername").Value)
End If
If not HttpContext.Current.Request.Cookies("User_Type") Is Nothing Then
Type = Server.HtmlEncode(Request.Cookies("User_Type").Value)
End If

FindControl() not getting value from input textbox

I am working on a website that has input boxes which are capable of being edited. The boxes are populated from an SQL call on PageLoad() and each text box is assigned with the ID "txtz" and then the ID number from the SQL row.
I want the user to be able to edit the text box, and upon clicking a html button have the values from the input boxes stored in a variable that can be used to Update the SQL data.
My issue is that when I call CType(FindControl it is having difficulties locating the instance of the object... I would be very grateful for any and all help!
Note When I alert the variable created for the input ID it matches what is displayed as the inputs ID on the browser... leaving me to think the FindControl function is the issue.
I have attached two images from my code in hopes that it may assist!
Table Creation in PageLoad
Procedure on Button Click
Sub UpdatePostDB(sender As Object, e As EventArgs)
Dim ButtonID As String = sender.ID
Dim ButtonID2 As String() = ButtonID.Split("z")
Dim placeholder As String = ButtonID(0)
Dim realID As String = ButtonID(2) & ButtonID(3) & ButtonID(4)
Dim titleinput As String = "txtz" & realID
Dim messgeinput As String = "txtz" & realID
Dim Titl As String = CType(FindControl(titleinput), HtmlInputText).Value
Dim Messge As String = Request.QueryString("txt2z" & realID)
ClientScript.RegisterStartupScript(Me.GetType, "titlealert", "alert('Title: " & titleinput & "');", True)
End Sub
cm1.CommandText = "SELECT * FROM ManagerPosts WHERE Department = '" & DeptDDL2.SelectedItem.Text & "' And DateAdded >= DATEADD(DAY,-14,GETDATE()) ORDER BY DateAdded ASC"
dr1 = cm1.ExecuteReader
If dr1.HasRows Then
While dr1.Read
Dim viewannouncement As New TableCell() With {.HorizontalAlign=HorizontalAlign.Center}
Dim viewannounce As New CheckBox With {.ID = dr1.Item("ID"), .AutoPostBack = True}
AddHandler viewannounce.CheckedChanged, AddressOf viewannounce_CheckedChanged
Dim updateCell As New TableCell()
Dim updatebutt As New Button With {.ID = "bz" & dr1.Item("ID"), .Text = "Update Post", .Height = 25%, .Width = 85%}
AddHandler updatebutt.Click, AddressOf UpdatePostDB
Dim tr As New TableRow
If dr1("Visible") = "N" Then
tr.Cells.Add(New TableCell With {.Text = "<div style='background-color:white'><input runat='server' id=txtz" & dr1.Item("ID") & " type='text' style='width:100%;' value='" & dr1("Title") & "'/><br /><input id=txt2z" & dr1.Item("ID") & " type='text' style='width:100%;' value='" & dr1("Message") & "'/></div"})
viewannouncement.Controls.Add(viewannounce)
tr.Cells.Add(viewannouncement)
ManageTable.Rows.Add(tr)
updateCell.CssClass = "buttonup"
updateCell.Controls.Add(updatebutt)
tr.Cells.Add(updateCell)
ManageTable.Rows.Add(tr)
Else
tr.Cells.Add(New TableCell With {.Text = "<div style='background-color:white'><input id=txtz" & dr1.Item("ID") & " type='text' style='background-color: #ff66ff; width:100%;' value='" & dr1("Title") & "'/><br /><input id=txt2z" & dr1.Item("ID") & " type='text' style='background-color: #ff66ff; width:100%;' value='" & dr1("Message") & "'/></div"})
If dr1.Item("ID") = viewannounce.ID Then
viewannounce.Checked = True
End If
viewannouncement.Controls.Add(viewannounce)
tr.Cells.Add(viewannouncement)
ManageTable.Rows.Add(tr)
updateCell.CssClass = "buttonup"
updateCell.Controls.Add(updatebutt)
tr.Cells.Add(updateCell)
ManageTable.Rows.Add(tr)
End If
End While
End If
**Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 146: Dim messgeinput As String = "txtz" & realID
Line 147:
Line 148: Dim Titl As String = CType(FindControl(titleinput), HtmlInputText).Value
Line 149: Dim Messge As String = Request.QueryString("txt2z" & realID)
Line 150:**

JSON.net - Using VB.NET Unable to iterate through results

I am trying to process this json document using JSON.NET.
With the VB.NET code:
Dim o As JObject = JObject.Parse(json)
Dim results As List(Of JToken) = o.Children().ToList
Dim count As Integer = 0
For Each item As JProperty In results
Dim snippet As String = String.Empty
Dim URL As String = String.Empty
Dim source As String = String.Empty
item.CreateReader()
Select Case item.Name
Case "response"
snippet = item.Last.SelectToken("docs").First.Item("snippet").ToString
URL = item.Last.SelectToken("docs").First.Item("web_url").ToString
source = ControlChars.NewLine & "<font size='2'>" & item.First.SelectToken("docs").First.Item("source").ToString & "</font>" & ControlChars.NewLine
tbNews.Text &= "<a href=" & URL & " target='new'>" & snippet & "</a> - " & source
End Select
Next
I am only receiving the first document as a result. Can someone advise as to how I can get the 1st - Nth documents as a complete list?
The docs are 2 levels deep, you're only looping in the top level. Try this...
Dim parsedObject = JObject.Parse(json)
Dim docs = parsedObject("response")("docs")
For Each doc In docs
Dim snippet As String = doc("snippet")
Dim URL As String = doc("web_url")
Dim source As String = doc("source")
'....
Next

ASP.net Gridview does not display first row

SqlDataReader myReader1 = null;
SqlCommand myCommand1 = new SqlCommand("SELECT Standard_Note_Code, COUNT(Standard_Note_Code) as Count FROM [Excel_table] where Standard_Note_Creator_Name = '" + ddlrep.Text + "' and (Std_Note_Date_Entered >= '" + datefrom + "' and Std_Note_Date_Entered <= '" + dateto + "') group by Standard_Note_Code", myConnection);
myReader1 = myCommand1.ExecuteReader();
myReader1.Read();
gvsummary.Visible = true;
if (myReader1.HasRows)
{
gvsummary.DataSource = myReader1;
gvsummary.DataBind();
}
else
{
myReader1.Close();
//myConnection.Close();
//Label2.Text = "No Records Exist";
}
myReader1.Close();
Remove myReader1.Read();, after ExecuteReader. That line causes the grid to start reading from the 2nd position.
Everything looks correct to me, except I don't think you should be calling
myReader1.Read();
before you bind to the GridView. I think if you remove that line it will fix your problem.
Don't call myReader1.Read(); if you're binding as a data source.

Resources