Response.write and ASP.NET controls - asp.net

Please see the code below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Response.Write("<table><tr><td>some text</td></tr></table>")
Response.Flush()
Threading.Thread.Sleep(3000)
Response.Write("<table><tr><td>some text</td></tr></table>")
Response.Flush()
Threading.Thread.Sleep(3000)
Response.Write("<table><tr><td>some text</td></tr></table>")
Response.Flush()
Threading.Thread.Sleep(3000)
Response.Write("<table><tr><td>some text</td></tr></table>")
Response.Flush()
Threading.Thread.Sleep(3000)
End Sub
The code works as I would expect i.e. a HTML table is generated and written to the screen, then after three seconds another table is generated and added to the screen etc.
I have a webpage that dynamically adds x number of tables (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.table%28v=vs.110%29.aspx) to a webpage. However, Response.Flush does not seem to work. I have created the simple code below to explain the problem:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim Table1 As New Table
Dim r As New TableRow()
Dim c As New TableCell()
c.Text = "Test 1"
r.Cells.Add(c)
Table1.Rows.Add(r)
Response.Flush()
Threading.Thread.Sleep(3000)
Dim Table2 As New Table
Dim r2 As New TableRow()
Dim c2 As New TableCell()
c.Text = "Test 2"
r.Cells.Add(c)
Table1.Rows.Add(r)
End Sub
Is it possible to flush table1 to the client, then wait a few seconds then flush table2 or do you have to write a string to response.write?

To use Response.Flush in that way you need to output all the HTML code yourself using Response.Write.
You can't use web controls as they are not rendered until the page is complete. The web controls only exist as objects until the Page_Render stage where the entire page is rendered as HTML code and then sent to the browser.

Related

How to keep DataTable persistent?

I have a Gridview filled by a dataTable, filled by a DataAdapter. That's how grid is initially loaded in Page_Load.
To add a search funcionality, I make the same but passing TextBox.Text as parameter to the SELECT... LIKE ... statement.
To add an edit funcionality(a button in every row) I need the previous data in the dataTable, and if I performed a search before editing I need only the result of the search in my dataTable.
The problem is, I don't know how to keep its value alive (persistent), and dataTable has 0 columns when I press teh edit button, so it doesn't display anything to edit.
I guess it happens because I'm using Using, and dataTable is probably getting cleaned after End Using.
In that case, whta can I do to fix it? I thought removing miconn.Close() but it doesn't solve anything, in fact, I don't know if connection is still open after End Using.
Code:
Dim con As New Connection
Dim table As New DataTable()
Private Sub fill_grid()
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
fill_grid()
End If
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim miCon As New Connection
Using miconn As New SqlConnection(miCon.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA WHERE area LIKE #area"
Using command As New SqlCommand(sql, miconn)
command.Parameters.Clear()
command.Parameters.Add("#area", SqlDbType.VarChar).Value = "%" + TextBox1.Text + "%"
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = table
GridView1.DataBind()
End Sub
Protected Sub CancelEditRow(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
GridView1.DataSource = table
GridView1.DataBind()
End Sub
BindGrid()
{
var dt = YourMethodReturningDatatable();
ViewState["Table"] = dt;
grid.DataSource = ViewState["Table"];
grid.Databind();
}
page_load
{
if(not ispostback) // not because my 1 key stopped working.
{
BindGrid();
}
}
I would suggest you to make two different functions for filling the data table and binding it. Call the filling function before the !IsPostBack condition and do the binding inside the condition. Here is the sample code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim table as new DataTable
table = GetData() 'The function that would return a data table
If Not IsPostBack Then
GridView1.DataSource = table
GridView1.DataBind()
End If
End Sub
Private Function GetData() As DataTable
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GetData = table
miconn.Close()
End Using
End Using
End Using
End function
Hope it helps.

CheckBoxList.Selected keeps coming back with False value

I have a CheckBoxList on my page that isn't behaving very well.
The idea is that once the submit button on the form is clicked, the app should clear the database table of all rows pertaining to the specific user and then re-insert new ones based on the user's CheckBoxList selections.
The problem is that regardless of whether or not any (or all) items in the CheckBoxList are selected, the app keeps getting Selected = False.
Here's my code:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
loadRegions()
End Sub
Private Sub loadRegions()
Dim db As New Database
Dim sql As String = "select * from regions"
Dim dr As MySqlDataReader = db.execDB(sql, "Text", Nothing, "DataReader", False)
If dr.HasRows Then
cblRegion.DataSource = dr
cblRegion.DataTextField = "regionname"
cblRegion.DataValueField = "regionid"
cblRegion.DataBind()
End If
dr.Close()
End Sub
Protected Sub btnRegister_Click(sender As Object, e As System.EventArgs) Handles btnRegister.Click
' ============================================================
' There's more code in here, but it's irrelevant to this paste
' ============================================================
Dim sql As String = "delete from userregions where userid = " & lblUserID.Text & ";"
For i As Integer = 0 To cblRegion.Items.Count - 1
If cblRegion.Items(i).Selected Then
sql &= "insert into userregions (userid, regionid)" & _
"values(" & UserID & ", " & cblRegion.Items(i).Value & ")"
db.execDB(sql, "Text", Nothing, "None", False)
End If
Next
End Sub
For the record
I'm aware of the potential for SQL Injection here. I'll be going over to using Parameters as soon as I have the loop working.
Thanks for your time.
Any help will be greatly appreciated.
You only need to call loadRegions on the initial load and not on postbacks:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
loadRegions()
End If
End Sub
Otherwise you'll lose changed values and events are not triggered.
Add this line of copde "If IsPostBack Then Return" in Page_Load method.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then Return
loadRegions()
End Sub
In page loaded, write the following:
If Not IsPostBack
loadRegions()
End If

change textbox's value from pageload event, submit new values issue

I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

Why is this insert code inserting data twice on button clicks?

The following code inserts same data two time in database table, but I want it to insert only one item when button is clicked.
What is the problem in this code?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If RadUpload1.UploadedFiles.Count >= 0 Then
Dim file As UploadedFile = RadUpload1.UploadedFiles(0)
SqlDataSource1.InsertParameters("photo").DefaultValue = "./upload/" & file.GetName()
'SqlDataSource1.InsertParameters("name").DefaultValue = TextBox1.Text
SqlDataSource1.Insert()
ListView1.DataBind()
End If
'UpdateProgressContext()
End Sub
You must be using both OnClick="Button1_Click" in your markup and Handles Button1.Click in your procedure.
Try removing one of them.

VB.NET CheckboxList doubles when button is clicked. Why?

Every time I click the Delete Button, the check marks double in quantity:
Public Class About
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim di As New IO.DirectoryInfo("C:\Images\")
Dim imageArray As IO.FileInfo() = di.GetFiles()
Dim image As IO.FileInfo
'clear imageArray
'list the names of all images in the specified directory
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click
For count As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(count).Selected Then
File.Delete("C:\Images\" & CheckBoxList1.Items(count).ToString)
End If
Next
End Sub
End Class
The checkboxlist isn't refreshed so that the checkbox that I deleted is removed from the checkboxlist. How do I accomplish that? Thanks!
On a button click, Page_Load is ran again, so the code that adds the checkboxes is ran a second time.
Add a check for Page.IsPostBack, and only add the checkboxes if it is not a postback.
If Not Page.IsPostBack Then
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End If
(I hope syntax is right... Not used to VB)
the whole content of the Page_Load event handler has to be executed only once in your case, so rewrite it like this:
If Not IsPostBack Then
Dim di As New IO.DirectoryInfo("C:\Images\")
Dim imageArray As IO.FileInfo() = di.GetFiles()
Dim image As IO.FileInfo
'clear imageArray
'list the names of all images in the specified directory
For Each image In imageArray
CheckBoxList1.Items.Add(image.Name)
Next
End If

Resources