vb.net to reduce code for displaying data in textboxes - asp.net

On the page I have created I have a search facility that if a doctors number is searched it will bring up the doctors details, once search button is clicked the results are displayed in textboxes (I cannot use gridviews because this is not wanted)
sample of code placed on the search button
Query statement = "SELECT DocNumber FROM tblDoctor WHERE DNum LIKE '%"
execute the query and get the result
The result is converted to string and Execute Scalar is used
DocNum.Text = Result1
Query statement = "SELECT DocName FROM tblDoctor WHERE DNum LIKE '%"
execute the query and get the result
The result is converted to string and Execute Scalar is used
DocName.Text = Result2
etc.... there are are 14 other textboxes that I want too display data in, so there is a large amount of repeated lines of code following the structure above. Can anyone suggest a better way of doing this?
Another problem of repetition of code comes from the prev page that is linked to it. The page before has a summary of details of doctors, once the row is clicked it takes you to this page displaying a more detailed view of their personal details. The doctor number selected will be passed onto the more detailed view using a querystring so I have the code
Automatic population of the selected doctors will fill the labels
on page load
Request the query string and store into variable dNum
Query statement = "SELECT DocNumber FROM tblDoctor WHERE DNum = " & dNum"
Get result from query convert to string and use execute scalar
lblDocNum.Text = Res1
Query statement = "SELECT DocNumber FROM tblDoctor WHERE DNum = " & dNum"
Get result from query convert to string and use execute scalar
lblDocNum.Text = Res1
etc...
What I am doing works correctly but the coding style looks poor. Any help would be much appreciated.
Thank you

Why not use a DataReader or DataSet or whatever you prefer to return the whole record, then simple move from column to column and populate the textboxes that way? Instead of returning one value at a time.

If the goal is less code,
SELECT * FROM tblDoctor WHERE xxx
into a DataTable or DataReader, as Thyamine suggested, above.
From there, you could also put the textboxes in an HTML table in a Repeater which you will bind to that datatable. You won't have to individually assign any of the values, the databinding will do it for you!
I know that people think HTML tables are evil but it's the easiest way to line up the labels I assume you will also want.
I also know that the control I suggested is called a Repeater but you only have one record. If you don't tell the compiler, I won't. :)
From parts of your question, it sounds like you're wondering whether to send all of the bits of information along in the querystring but that doesn't sound like a good idea to me because it invites users to mess with the data in the querystring.
You didn't mention - are these textboxes meant for editing? A Save button inside the Repeater would have easy access to all of the controls to build your update statement. You could also put the Save button outside the repeater and refer to the repeater's first Item to find the controls.

Related

A list(of String) I have fails to populate on a post back but populates just fine on the initial page load

I am relatively new to programming so please bare with me if I use improper terminology for the question I am about to ask.
Currently, I have a list(of String) that I am populating with 2 values that I am pulling from a database. Code Below.
objCn.Open()
sqlTermSelect.Connection = objCn
sqlTermSelect.CommandText = "Select PartsTerm, LaborTerm FROM SKU INNER JOIN Agreement On SKU.SKU = Agreement.SKU WHERE Agreement = #Agreement"
sqlTermSelect.Parameters.Add("#Agreement", SqlDbType.VarChar, 50).Value = txtAgreement.Text
Dim termDA As New SqlDataAdapter(sqlTermSelect)
Dim termDT As New DataTable()
termDA.Fill(termDT)
For i As Integer = 0 To termDT.Rows.Count - 1
listValues.Add(termDT.Rows(i)("PartsTerm").ToString())
listValues.Add(termDT.Rows(i)("LaborTerm").ToString())
Next
objCn.Close()
I am then storing the values of this list in two variables that I use as checks to see whether certain controls on my page should be enabled/visible or disabled/invisible.
The page that this is affecting operates(for lack of a better word) in two ways, the first is a brand new page with empty controls that the user fills out. The second way is if the user begins to fill out the page and leaves, the data they filled out is saved and they can return later to continue filling it out (I am not 100% certain but I believe when a user returns to an "in progress" page it is a post back, I could be wrong, I'm not terribly sure how this is handled).
The problem I am having comes to when this list is populated with the database values. When I go to a brand new page, the list is populated and the controls mentioned above are enabled/disabled appropriately with no issues, the issue arises when I go to an "in progress" page the list values don't populate and the controls that should be disabled are enabled. Essentially, I am looking for a way to populate this list every time a page is opened, "in progress" or brand new. The code above that populates the list is in the PageLoad() event and I have verified that it is not in a "If Not IsPostBack" statement.
Any and all help would be greatly appreciated, if there is anything I should add to this post code related I would be more than happy to supply it.

In App Maker, how do you make dynamic table cell text?

In App Maker, I am displaying a table and want to replace table cell data with different text using a data lookup from another table. Assume two tables, Departments and Employees.
Departments is two fields, DeptID and DeptDescription.
Employees is multiple fields including DeptID.
In the table listing for Employees, I would like to replace the DeptID with the DeptDescription. (The page datasource is Employees. I do not want to set up a relationship between the data models.)
I am guessing I want to do some scripting in the onDataLoad event for the table cell label for DeptID. I have this much so far:
app.datasources.Departments.query.filters.DeptID._equals = widget.datasource.item.DeptID;
app.datasources.Departments.newQuery().run();
widget.text = app.datasources.Departments.item.DeptDescription;
I know this is not correct, but am I close?
This answer is untested, but I wanted to present a possible solution that would not require a lot of DB calls, especially ones that make repeated calls to a server script which might consume a lot of processing time when you do line item calls.
Set up a separate datasource under the Department model. Change the default 'Query Builder' to 'Query Script' and add a parameter of type 'list(number)' or 'list(string)', this should match your Primary Key field type. Uncheck the 'auto load' option.
In your 'Query Script' portion enter the following code:
query.filters.Id._in = query.parameters.YourParameter;
return query.run();
Go to your Employees datasource that is supposed to generate your table and find your 'On Load' client script section. In this section enter the following code:
var departmentsDs = app.datasources.YourDepartmentsDs;
departmentsDs.properties.YourParameter = datasource.items.map(function(deptIds) {return deptIds.DeptID;});
departmentDs.load();
Now go the page that contains your table. If you have not already create a label widget do so now. In this label widget for the text binding enter the following:
#datasources.YourDepartmentsDs.loaded && (#datasources.YourDepartmentsDs.items).map(function(Id){return Id.Id}).indexOf(#widget.datasource.item.DeptID) !== -1 ? #datasources.YourDepartmentDs.items[(#datasources.YourDepartmentsDs.items).map(function(Id){return Id.Id}).indexOf(#widget.datasource.item.DeptID)].DeptDescription : 'Unable to retrieve Dept Description'
As stated this is untested and I wrote the code from memory without App Maker in front of me so it may require some additional tweaking. Going with the first option presented by J.G. would also be a very viable solution though. And I apologize but the code formatter does not seem to be working for me.
1 way) Create an aggregate table that joins your tables if you need to bypass using the relations feature. This way you can use sql to join the two tables in the datasource definition
2) if you don't want to make a new table. Change the text from a value binding to "more options"
=getDescription(#datasource.item.DeptId)
and then the code you wrote in a client side script
function getDescription(id){
google.script.run
.withSuccessHandler(function successHandler(result){ return result;})
.withFailureHandler( function failureHandler(e){ console.log(" Failed" +e);})
.queryValue(id);
}
server side script:
function queryValue(id){
var query = app.models.Departments.newQuery();
query.filters.DeptID._equals = id;
var results = query.run();
return results[0]["DeptDescription"];
}
that last line might be results[0].DeptDescription

use dynamic data in dreamweaver CS6 to populate a hyperlink

Basically I have a news page which stores headlines, stories, and a unique story identifier in a SQL database. I want to be able to create a hyperlink on a webpage to the pictures.
so when someone selects a news story from a drop down menu (which uses the headline) and presses submit I want to pass the storyID, which is a unique identifier, to a spot in a hyperlink. so if it was story 134 then then link would look like:
I know the SQL statement would look like:
SELECT StoryID from db.News
Where Headline = {The headline selected in the dropdown menu}
the dropdown menu is called NewsDrop
this would be an ASPX page written with a VB code base
SO I guess I need help passing the variables along to the search string and the hyperlink.
Not even sure if this is even possible.
There are a number of options available to achieve this, the most common would be to using a query string in the hyperlinks in your drop down menu to send a parameter to a SQL stored procedure which would use it in a variable in your select statement. So basically the hyperlinks you have in the drop down menu would be appended with ?storyID=<uniquestoryid> and on the far end SELECT StoryID from db.News Where StoryID = #StoryID it would be less efficient to use the headline from the link as a query string and variable in the where clause as you have shown but if that is your only option it could be done.
However you should proceed carefully when using query strings here is a link to a good basic article about query strings and another link about best practices.

Iteratively Reference Controls by Name Pattern (VB.NET)

Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something?
What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item.
'TextBoxControl & DropDownListControl should iteratively reference their
' respective TextBox & DropDownList controls by the actual control name
If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then
'When an Existing Item is selected, Do Something
ElseIf Not TextBoxControl.Text = "" Then
'When a New Item is entered, Validate & Do Something
Else
'When NULL, Do Something
End If
The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively.
I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls:
Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb"
Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database.
Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere.
Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption.
I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use:
Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value
where controls encompasses all controls on the userform ("Me"). So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net

Update Field in ADO Recordset and Re-sort values in Classic ASP

Here's the current situation: I have a recordset of products. The price of these products depends upon other information elsewhere on the page. So, as I loop through the recordset for output, I calculate the price using a function, and display it. This all works wonderfully.
Now, for the new wrinkle. I need to be able to sort the products by the calculated price before I display them. My attempt was to simply add a new field to the recordset, loop through the recordset once to calculate the price and update that new field, and then resort the recordset on that field before looping again for the display.
Needless to say, this does not work. No matter what settings (lockType, cursorType, cursorLocation) I put on this recordset, I am presented with an error stating "Current Recordset does not support updating. This may be a limitation of the provider, or of the selected locktype."
Is there any way to make this work as described, or is there another method of accomplishing this result? For reference, here is the code snippet that I am currently working with.
set rsProd = server.CreateObject("adodb.recordset")
rsProd.cursorType = adOpenKeyset
rsProd.lockType = adLockPessimistic
rsProd.cursorLocation = adUseServer
rsProd.Open sql, Conn1
'loop through the records and calculate prices'
Do until rsProd.EOF
laPrices = Split(GetParameterProductPrice(rsProd("Product_ID")), "|")
'ERROR OCCURS ON NEXT LINE'
rsProd("Sale") = CDbl(laPrices(0))
rsProd("Sale_Special")= CDbl(laPrices(1))
rsProd.MoveNext
Loop
rsProd.MoveFirst
rsProd.Sort = "Sale_Special, Sale, Product_Code"
One way to accomplish this would be a computed column in your database.
The main benefit would be that you wouldn't need to change your page(s). Additionally you could reuse the calculated price in other places in your application - I guess you actually calculate the price again on other parts of the site.
If this recordset is not huge, one solution is during your loop, store your calculated price into an array. Once you've calculated the pricing, you can sort the array with a sorting function and then print out the results.

Resources