How to get the value on the textbox in server vb.net - asp.net

I have created a textBox in the server side(vb.net) like this:
Dim r As New TableRow
Dim c As New TableCell
Dim txt As New TextBox
For i = 1 To 10
c = New TableCell
txt = New TextBox
txt.ID = "recev" & i
txt.ClientIDMode = UI.ClientIDMode.Static
Next
This create me all the textBox in my page.
Now the user need to enter numbers in the textBox and press on OK button.
My problem is that I don't know how to get the numbers.
If I do in the html <form> so I can do this:
For i = 1 To 10
txt = "recev" & i & ""
Request.Form(txt)
Next
and it's work. But I can't use <form> because of other reasons.
Can I use something else to get the data the user insert?
Thanks!

For example, you could use Javascript, in this way:
Event 'click' of your button: javascript:process_stuff();
Your javascript, would be something like this:
function process_stuff(){
var your_values = [];
for (var indice = 1; indice <= 10 ; indice++) {
if ($("#recev" + indice).length){
your_values[indice ] = $("#recev" + indice).val();
}
PageMethods.PM_receipt_info(your_values);
}
Server side:
<WebMethod()> _
Public Shared Sub PM_receipt_info(aValues)
for each sValue as String in aValues debug.print(sValue ) next
Where aValues is an array with the textboxes values'.
Another try: if you need a postback, can do it JS __doPostBack ('',params), passing that values sepparated with character , etc.

Related

Count visitor of one page in asp.net

I have a page that contains a record of a database. I want to count number of visits of that page . I use codes below to counts number of visits of page by increment view field of record. but this increment view randomly. for example when I refresh page the view increment 20 !.
my codes for this page is:
protected void Page_Load(object sender, EventArgs e)
{
da db = new da();
string str = "select views from newstxt where id=" + Request.Params["id"].ToString();
DataTable dt = new DataTable();
dt = db.select(str);
int view = Int32.Parse(dt.Rows[0][0].ToString());
//increment
view++;
//
str = "update newstxt set views=N'{0}' where id=" + Request.Params["id"].ToString();
str = string.Format(str, view);
db.docom(str);
}
There are couple of ways for this approach
simple approach would be using a view state
declare a Property like
public int ViewCount
{
get { return (int)ViewState["viewcount"]; }
set { ViewState["viewcount"] = value; }
}
use like ViewCount++; on page load and to get value int value = ViewCount
i hope this helps !!!
Protected Sub Page_Load(sender As Object, e As EventArgs)
Me.countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
End Sub
Private Sub countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())
hits += 1
tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()
tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
End Sub
XML
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
Nothing seems to be wrong with your code but it seems like there is something wrong your Request.Params. Are you using query string, if it is then i would suggest you to use Request.QueryString instead. Also, what you want only if to update the count then you can avoid select query and reduce your code to:
da db = new da();
String str = "UPDATE newstxt SET views = views + 1 WHERE id=" + Request.QueryString["id"].Trim();
db.docom(str);

Adding linebreak in loop

I use the following code to add smoe fileupload controls on my page. I'd like a line break between each one, but am having trouble getting it to work.
For i As Integer = 1 To 2
Dim fileupload As FileUpload = New FileUpload
fileupload.ID = "FileUp" & i
placeUpload.Controls.Add(fileupload)
Next
Thanks
For i As Integer = 1 To 2
Dim fileupload As FileUpload = New FileUpload
fileupload.ID = "FileUp" & i
placeUpload.Controls.Add(fileupload)
placeUpload.Controls.Add( new LiteralControl("<br />") )
Next

Programatically created ASP.NET TextBox retains Text value after PostBack even if Control is cleared

I have a drop down menu, and based on which item is selected, I call a web service and then dynamically create some text boxes.
The first time I drop down the menu and select an item, it works perfectly, and the text boxes are created and populated dynamically. However, the next time I drop down the menu (after the first postback), and select something different... after the second postback, the original values remain in the textboxes.
I am clearing all of the text boxes out of the placeholder, then re-creating them, and then setting a NEW value, how can they retain the OLD values... especially if I controls.clear them from the page?
Note: The second time they are being created, the textbox IDs DO end up being the same. Could that have something to do with it? This duplicate ID functionality will need to be supported.
My code, called from Page_Load, is as follows: (edited to add more code)
Private Sub RefreshEntity()
Dim XmlRecords As New XmlDocument
Dim XmlRecordsNode As XmlNode
Dim EntityType As String = EntityTypes.SelectedValue
Dim Entity As String = RecordValue.Value
Dim FieldName As String
Dim FieldValue As String
FieldPlaceHolder.Controls.Clear()
If RecordList.SelectedValue <> "Select..." Then
Try
XmlRecordsNode = LoginInfo.SharePointConnectWebService.GetMetaData(LoginInfo.WSUser, LoginInfo.WSPass, _
EntityType, Entity)
XmlRecords.LoadXml(XmlRecordsNode.OuterXml)
Catch ex As Exception
ConfirmLabel.Text = "<b>Error:</b><br>" & ex.Message.ToString
Return
End Try
Else
SetProperties.Visible = False
Return
End If
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
newLabel.Text = FieldName & ": "
Dim newTextBox As TextBox = New TextBox()
newTextBox.ID = "Field-" & FieldName
newTextBox.Text = FieldValue
Dim newLine As Label = New Label()
newLine.Text = "<br><br>"
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
Next
SetProperties.Visible = True
End Sub
And the RecordValue.Value is a hidden field that gets populated in every Page_Load:
RecordValue.Value = RecordList.SelectedValue
Where RecordList is my DropDown menu.
This is likely due to ViewState or the Posted values clobbering your values.
Once a control is dynamically added to the controls collection it needs to catch up with all the page life cycle events that have already fired. In the case of a post back this means that the ViewState and/or the posted form value will clobber the .text property on the TextBox based on the order you're adding the dynamic controls to the controls collection and setting the .text property.
To fix this you can disable ViewState by setting the .EnableViewState property to false on the dynamically generate controls also add the controls to the controls collection before you set any properties on them.
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
Dim newTextBox As TextBox = New TextBox()
Dim newLine As Label = New Label()
newTextBox.ID = "Field-" & FieldName
newLabel.EnableViewState = False
newTextBox.EnableViewState = False
newLine.EnableViewState = False
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
newLabel.Text = FieldName & ": "
newTextBox.Text = FieldValue
newLine.Text = "<br><br>"
Next
You're not storing the value in a Session variable and then putting it back into the text box later in your code?

How do I use id's of HTML elements in another sub when they are created from server-side code?

I have a table that I'm creating in code behind with the final column containing a HTML checkbox with runat="server".
The code I'm using to do this is:
Do While reader.HasRows
Do While reader.Read
Dim tNewRow As New HtmlTableRow
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
cellSelect.InnerHtml = "<input type='checkbox' id='selectedSKU' value='" & reader("SKUN") & "' runat='server' />"
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
But I want to use the checkbox in another sub such as:
Protected Sub editSkus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles editSkus.Click
End Sub
Though I can't use selectedSKU.whatever as the checkbox doesn't exist on the page until the other section of code is run.
Is there a way I can get around this or another way of doing things?
Thanks in advance for any help.
It's nasty, but here goes...
Dim skusTable As New HtmlTable
Dim i As Integer
Do While reader.HasRows
Do While reader.Read
i = i + 1
Dim tNewRow As New HtmlTableRow
tNewRow.ID = "MyRow" & i
Dim cellSKU, cellDESCR, cellDept1, cellDeptGrp1, cellDeptRng1, cellStand, cellBoard, cellSelect As New HtmlTableCell
cellSKU.InnerHtml = "<a href='edit.aspx?edit=" & reader("SKUN") & "'>" & reader("SKUN") & "</a>"
cellDESCR.InnerText = reader("DESCR")
cellDept1.InnerText = reader("DPT1")
cellDeptGrp1.InnerText = reader("GRP1")
cellDeptRng1.InnerText = reader("RNG1")
cellBoard.InnerText = reader("BOARD")
cellStand.InnerText = reader("STAND")
'Create the checkbox as a webcontrol and add it to the table cell
Dim checkBox As New HtmlControls.HtmlInputCheckBox
checkBox.Value = reader("SKUN")
checkBox.ID = "selectedSKU"
cellSelect.ID = "SelectedCell"
cellSelect.Controls.Add(New WebControls.CheckBox)
tNewRow.Cells.Add(cellSKU)
tNewRow.Cells.Add(cellDESCR)
tNewRow.Cells.Add(cellDept1)
tNewRow.Cells.Add(cellDeptGrp1)
tNewRow.Cells.Add(cellDeptRng1)
tNewRow.Cells.Add(cellStand)
tNewRow.Cells.Add(cellBoard)
tNewRow.Cells.Add(cellSelect)
tNewRow.Style.Add("border", "solid 1px #cccccc")
skusTable.Rows.Add(tNewRow)
Loop
reader.NextResult()
Loop
Now all you need do is use FindControls to get to the element...
Dim myRow As HtmlControls.HtmlTableRow = skusTable.FindControl("MyRow" & i)
'Probably be good to check the object exists first....
If Not myRow Is Nothing Then
Dim myCell As HtmlControls.HtmlTableCell = myRow.FindControl("SelectedCell")
If Not myCell Is Nothing Then
Dim myCheckbox As HtmlControls.HtmlInputCheckBox = myCell.FindControl("selectedSKU")
If Not myCheckbox Is Nothing Then
'Got it! now is it selected?
Return myCheckbox.Checked
End If
End If
End If
The runat="Server" attribute is parsed by the ASP.NET process and indicates that it should create some kind of control object. At the point your code is running this parsing has already been done. ASP.NET does not parse content added to the InnerHTML property to look for additional runat attributes or any other ASP.NET specific markup, InnerHTML is expected to be strictly standard HTML that is to be sent to the server.
You could create an instance of the CheckBox ASP.NET control and add it to the cellSelect controls collection, which is the equivalent to runat="Server". However that doesn't really help because you want to bind an event to this control but on post back this control will no longer exist.
Is there a reason you are not using DataGrid to acheive this UI?

how to clear off gridview?

I'm creating a dynamic gridview function which will bind different tables from DB into a datatable and then assign the datatable to the gridview! This is how it works, i have a dropdownlist, gridview and a button, the button will fire specific function based on the dropdownlist selection and then gridview will bind the data, my problem is that, when u press the button for the 1st time, the gridview will bind the data from DB, for second time pressing, the gridview will duplicate the data from the data of 1st time pressing! how do i clear off the gridview to avoid data duplication?
Private Sub Login()
sSql = "" & _
"SELECT TYPE, SUBTYPE, LOGTS, ACTION, USERID, STAT1 " & _
"FROM i_LOG " & _
"WHERE TYPE = 'USR' AND SUBTYPE = 'LOG' " & _
"AND CONVERT(VARCHAR(20), LOGTS, 103) >= '" & txtDTFrom.Text & _
"' AND CONVERT(VARCHAR(20), LOGTS, 103) <= '" & txtDTTo.Text & "'"
DT = CreateDataTable(sSql) 'Retrieve from database.
Session(sSesDT) = DT
GVM.DataTable = DT
GVM.GVAddEmptyRow()
Dim seq As New BoundField
Dim Type As New BoundField
Dim SubType As New BoundField
Dim Logts As New BoundField
Dim action As New BoundField
Dim user As New BoundField
Dim status As New BoundField
seq.HeaderText = GVM.DTNumberField
seq.DataField = GVM.DTNumberField
Type.HeaderText = "Type"
Type.DataField = "TYPE"
SubType.HeaderText = "Subtype"
SubType.DataField = "SUBTYPE"
Logts.HeaderText = "Date and Time"
Logts.DataField = "LOGTS"
action.HeaderText = "Action"
action.DataField = "ACTION"
user.HeaderText = "User ID"
user.DataField = "USERID"
status.HeaderText = "Status"
status.DataField = "STAT1"
gv.AutoGenerateColumns = False
gv.Columns.Add(Type)
gv.Columns.Add(SubType)
gv.Columns.Add(Logts)
gv.Columns.Add(action)
gv.Columns.Add(user)
gv.Columns.Add(seq)
gv.Columns.Add(status)
gv.DataSource = Session(sSesDT)
gv.DataBind()
End Sub
Private Overloads Function CreateDataTable(ByVal sSql As String) As DataTable
Dim DA As New OleDb.OleDbDataAdapter
Dim dtDataTbl As New DataTable
Dim dcDataCol As New DataColumn
With DBMgr
.openCnn()
.SQL = sSql
.openRst()
DA.Fill(dtDataTbl, .rst)
End With
'==Adding Columns==
dcDataCol = New DataColumn 'No
With dcDataCol
.DataType = GetType(Int32)
.ColumnName = GVM.DTNumberField
.AutoIncrement = True
'.AllowDBNull = True
End With
dtDataTbl.Columns.Add(dcDataCol)
'**Adding Columns**
Return dtDataTbl
End Function
Sorry, this is in C#, but just call it before you bind any new data and it'll clear any existing data... unless of course the problem is that the DataSource you are assigning has the duplicated data.
gridview.DataSource=null;
gridview.DataBind();
Also, just to note, you are adding every column in every time that procedure is called? You need to run:
gridview.Columns.Clear();
You can reset it's data source and rebind it for example
gv.datasource=""
gv.databind()
and then reuse it
Usually this does not happen when you rebind grid like:
grid.DataSource = 'NEW_DATA_SOURCE'
grid.DataBind
I think may be the problem is in your function fetching data:
CreateDataTable(sSql)
Please check inside this if you are fetching data every time into a new DataTable or using same one (may be declared at global scope or passed from your class to data accessing component). I'd lost whole night once to fix this :(
Place your gridview in a table with an id:
<table id="myTable" border="0">
<tr><td>
<asp:GridView Width="765px" ID="mygrid" runat="server">
...
...
</asp:GridView>
</td></tr></table>
Then call from a button click your javascript function:
function clearGridview()
{
var rows = document.getElementById('myTable').getElementsByTagName('tbody') [0].getElementsByTagName('tr').length;
if(rows!=0)
document.getElementById("myTable").deleteRow(0);
}

Resources