Get child page data from master page selectedItems - asp.net

I have location DropdownList in my master page. I have set control in my child page which takes properties from master page. Now I am running a query
SELECT * FROM table where city like '"+city.text+"'
here city.text gets value from master page selected cities. But my problem is it's not actually showing records as per city.text has values in it. It shows any random records.
My Code
Master Page
<asp:DropDownList ID="locationSelector" runat="server" AutoPostBack="true">
<asp:ListItem Selected>Pune</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Chennai</asp:ListItem>
<asp:ListItem>Bangalore</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
</asp:DropDownList>
Child page VB Code
Dim location As DropDownList = Page.Master.FindControl("locationSelector")
city.Text = location.SelectedItem.ToString
If Not IsPostBack Then
Try
query = "SELECT * FROM hospitals where city like '" + city.Text + "'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
ViewState("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
Catch ex As Exception
Response.Write(ex)
End Try
End If
UPDATE
Protected Sub hospitals_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim location As DropDownList = Page.Master.FindControl("locationSelector")
city.Text = location.SelectedItem.ToString
End Sub
Sometimes it also throws TimeOut error. But most of the time It gets results but not as per selected items. What will be any other solution for this?

A couple of tips:
1) Timeout errors can happen for a number of reasons, including lots of other traffic to the site, connection pools all used up etc. I would, for a small list of cities, maybe keep that in a cache after the first call, so that you do not need to load the city list from database every time. Depending on your country, if you only have a few thousand cities, then just put it in an in-memory list.
2) You are using a "SELECT *" which is usually not really cool to other developers, nor to your code if the table contains more than just a city name. IF you write Select CityName from Table, then you will effectively have reduced the amount of data going from your database to your program, and it is clear to the other developers exactly what you're pulling from that table.
3) If you have an ID for the city, it will likely perform even better as string matcing is REALLY slow compared to matching a couple of ID's. I've seen 20% speed improvements by replacing strings with constants, you wouldn't believe how slow strings are in code these days.
4) Last, and I think you may already have done this, make sure that you INDEX every field that you do a WHERE filter on. If you search for Hospitals, then make sure that the Hospitals.City field is indexed to avoid row lookups.
I hope (any) of this helps you :)

As per my understanding you need to change below
to fetch the selected TEXT value use location.SelectedItem.Text instead of location.SelectedItem.ToString()
city.Text = location.SelectedItem.Text // change here
before binding the dropdown control check the no. of rows
if(table.Rows.Count>0)
{
hospitals.DataSource = table;
hospitals.DataBind();
}

I would suggest to use prerender event within page. In prerender event try to access your master page control and get value.

Related

Create a Universal Function for a random Amount of ImageButtons located in a Random Amount of Div's Based on a Recordset

I have created a Web Form with a Container Div that is Populated with child Div’s
Based on Data Rows from an SQL Server. The Child divs each have an ImageButton and some labels that house the partial information about the Record. I have given the ImageButton the ID of the record Set (i.e “EST-011”) the intent is to Open a new Webform and pass the Data to the New web form
The problem is not passing information from one web form to another. I know how to do that. What I don’t know how to do is Make a Universal function for a random amount of ImageButtons Created in a Random Amount of Div’s as of now the function is not firing Nothing happens when I click the random ImageButton
I am coding in vb.net But any solution in CSS or Jscript is welcome
'Add control to div
MyIMGBttn.Style.Add("Runat", "server")
MyIMGBttn.Style.Add("OnClick", "CallOpenNewWebform ()")
MyIMGBttn.Style.Add("Value", "Click()")
MyIMGBttn.Style.Add("Class", "ChildImgBttn")
div.Controls.Add(MyIMG)
Function Open CallOpenNewWebform()
Dim JobName As String = Me.ID' will this get the id?
Response.Redirect(String.Format("~/Webform9.aspx?JobName={0}", JobName technology))
End Function
Webform9 on PageLoad event()' Just Shown for clarity fir fubal destination of data Key
Dim conStr As String
conStr = connString
Dim dt As New DataTable()
Dim field1 As String = Request.QueryString("JobName") ‘Info from the div For the Query
Try
Query Stuff Goes here.

Type-casting entity framework results in ItemDataBound

So I've trying to optimize performance of a page which generates the navigation menu for a website. Basically there is a table called T_product_cat which contains 4 fields I care about:
product_cat_name (the product category name)
product_cat_uid (the unique identifier of the row)
product_cat_thumbnail_path (the image that represents the category)
product_cat_parent_uid (the unique identifier of the product category
that we sit underneath - since these "product folders" can nest)
I need to create a top navigation bar which has just the names of the top level product categories and then for the dropdown navigation I need to output the sub product categories along with their images and links etc. I've got a basic ASP:Repeater control with a nested ASP:Repeater to handle the sub-product categories
Basically though I want to start using EF to start querying for my data. Initially I did a query to just pull the top level items and then in the ItemDataBound event of the repeater, I'd access the data and query the database again for the sub categories. But this was hitting the database 8x (since I've got 7 top level categories). To speed things up I've been trying different iterations of an initial query. Here's my final one for reference:
Using db As New RmpEntities
' query all the items and then all their subitems at the same time so that we don't have to repeatedly hit the database
Dim qry = (
From
productCat In db.T_product_cat
Where
productCat.company_uid = WmsSession.company_uid AndAlso
productCat.enabled = 1 AndAlso
productCat.product_cat_parent_uid = GUIDs.GlobalGuids.RootCategoryUid AndAlso
productCat.product_cat_hide <> 1
Order By
productCat.product_cat_sequence
Select
categoryName = productCat.product_cat_name,
categoryUid = productCat.product_cat_uid,
imagePath = productCat.product_cat_thumbnail_path,
subCategories = (
From
productSubCat In db.T_product_cat
Where
productSubCat.company_uid = WmsSession.company_uid AndAlso
productSubCat.enabled = 1 AndAlso
productSubCat.product_cat_parent_uid = productCat.product_cat_uid AndAlso
productSubCat.product_cat_hide <> 1
Order By
productSubCat.product_cat_sequence
Select
categoryName = productSubCat.product_cat_name,
categoryUid = productSubCat.product_cat_uid,
imagePath = productSubCat.product_cat_thumbnail_path
)
)
rptMainNav.DataSource = qry.ToList()
rptMainNav.DataBind()
End Using
When the repeater's ItemDataBound event fires I do have working code to pick apart the results and bind the data to the sub-repeater (this code works):
Protected Class CategoryInfo
Public Property categoryName As String
Public Property categoryUid As Guid
Public Property imagePath As String
End Class
Private Sub rptMainNav_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptMainNav.ItemDataBound
Dim rItem As RepeaterItem = e.Item
Select Case rItem.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim dataItem = rItem.DataItem
Dim subRepeater As Repeater = rItem.FindControl("rptSubNav")
Dim parentUid As Guid = dataItem.categoryUid
Dim st = DateTime.Now
Dim x As New List(Of CategoryInfo)
For Each item In dataItem.subCategories
x.Add(New CategoryInfo With {.categoryName = item.categoryName, .categoryUid = item.categoryUid, .imagePath = item.imagePath})
Next
subRepeater.DataSource = x
dTime.Add(New MyTimes With {.g = parentUid, .ts = DateTime.Now - st})
subRepeater.DataBind()
End Select
End Sub
But how can I cast the Object type returned by accessing the repeater's DataItem to a more strongly-typed object so I can get intellisense?
Or is there some way I can give up on the worries about typing and just use the query results directly as a DataSource for the sub-repeater? That was my first goal but when I tried to take
dataItem.subCategories.ToList()
It failed with:
Public member 'ToList' on type 'CompensatingCollection(Of VB$AnonymousType_1(Of String,Guid,String))' not found.
When I tried to modify my CategoryInfo class to have another property to hold a list of CategoryInfo classes (subcategories) and have the main query return structured data (so I'd have a type to cast to in the ItemDataBound) things failed even worse. The original query's .ToList failed so I couldn't even do the initial bind.
What is the correct way to handle this? Continue working on properties of an Object which represents an anonymous type? Surely there must be something better.
EDIT:
Robert - Thanks for your suggestions. It turned out that I did NOT have a navigation property to SubCategories. The reason being that the people who came before me designed the database such that all top level categories end up with an artificial product_cat_parent_uid (just some random GUID). It doesn't point to a real product category in the database - it just acts as a placeholder. I question why they didn't just use NULL but it's too late to change it. At any rate since the item doesn't exist in the database, the database itself doesn't have the foreign key since it's faking the link. The databse won't create the link with product categories pointing to a product categorie that is not in the database. I did use your suggestion to find more information about what could be done and I used this article (Entity Framework - Add Navigation Property Manually) to add those links I need.
The question still remains though - can I get strong typing within the ItemDataBind event?

Dataset in asp.net

I have a page in my website where a users can edit the records - one of the fields is a dropdown list.
I've been told I can use this code below to populate the dropdown field. My question is this; if several people are working in the page is the System.Data.DataTable created unique to the user? Many thanks.
Dim subjects As New System.Data.DataTable()
Dim queryStringN As String = "SELECT [UKEY], [ClientContact] FROM [View_Contacts] with (NOLOCK) order by [ClientContact]"
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("Databaseportal").ConnectionString)
Try
Dim adapter As New SqlDataAdapter(queryStringN, con)
adapter.Fill(subjects)
Me.ProductionManager1.DataSource = subjects
Me.ProductionManager1.DataTextField = "ClientContact"
Me.ProductionManager1.DataValueField = "ClientContact"
Me.ProductionManager1.DataBind()
' Handle the error
Catch ex As Exception
End Try
End Using
Each time the page is requested, it will generate a DataTable that will be unique to that instance of the Page, so the answer to your question is Yes, it will be unique to the user.
Your query looks generic and same for every user. There is no filter which can bring different record set for different users.
SELECT [UKEY], [ClientContact] FROM [View_Contacts] with (NOLOCK) order by [ClientContact]
In nutshell, it will yield same dataset for every user on your webpage. The data inside the datatable will be same for every user.

listbox selects wrong item

Update I have solved the issue, however will finish posting this (solved prior to posting) in hopes it might help someone else out.
Issue: Referencing and manipulating listitems from a listbox requires the listbox's listitems to all have unique listbox.value. In my case, I was assigning the tablename as the listbox value and the columname as the listbox.text(I was giving the user a list of fields from a sql table to choose from). So a listbox containing the following:
Index 0: Text:street Value:"dbo.incident"
Index 1: Text:city Value:"dbo.incident"
Index 2: Text:state Value:"dbo.incident" Selected
And you then reference textbox1.selected item via code, it's handling is unexpected.
It starts off knowing the selected item, but at some point in it's handling of the referenced listitem, it starts referencing it via value, at which point the return text or index would be 'street' or '0'. I understand once you start pulling items from a listbox, it pulls its first match.
begin original post
Okay project is a vb .net web forms project
I have 2 listboxes that I want to populate and move entries back and forth, up and down.
I understand how to do this, however i cannot seem to overcome this bizzare errant behavior that is happening.
If I add items manually like this it works fine, the listitems transfer between the listboxes and I can change the indexes as expected.
(for this post, I will refer to entries created this was as static)
ListBox1.Items.Add(New ListItem("1", "1"))
...through...
ListBox1.Items.Add(New ListItem("10", "10"))
However if I add them programaticly from a linq statement, manual selection in the web page holds no bearing on selected item, it is always 0, clicking any button on the page, postback returns the listbox to index 0.
(for this discussion, I will refer to entries created this way as dynamic)
Dim db As New MSCRMDataContext
Dim datamodel = db.Mapping
For Each r In datamodel.GetTables
If r.TableName = "dbo.IncidentFull" Then
For Each r1 In r.RowType.DataMembers
ListBox1.Items.Add(New ListItem(r1.MappedName, r.TableName))
Next
End If
Next
I have an aspx button:
<asp:Button ID="Button1" runat="server" Text="Button" />
That has the following click event:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
mlbs_transferitem(ListBox1, ListBox2, ListBox1.SelectedItem)
End Sub
I have the sub that transfers the listitem in a separate .vb file
Public Class multilistboxselector
Shared Sub mlbs_transferitem(srclb As ListBox, dstlb As ListBox, lbitem As ListItem, Optional sort As Boolean = False)
'checks if srclb had a selected listitem
If IsNothing(lbitem) Then
Exit Sub
End If
'check for dupes
For Each li As ListItem In dstlb.Items
If li.Text = lbitem.Text Then
If li.Value = lbitem.Value Then
Exit Sub
End If
End If
Next
'add lbitem to dst
dstlb.SelectedIndex = -1
dstlb.Items.Add(lbitem)
'remove lbitem from src
srclb.Items.Remove(lbitem)
'sort dst
If sort = True Then
End If
End Sub
Just to be clear, the code works flawlessly with the static entries. I have created a new page and recreated everything there and the I have the same experience as my source page.
Edit
Trimming out my troubleshooting steps as they prove irrelevant to the issue and were quite lengthy.

Access 2010: Display contents of multiple records to unbound controls in datasheet

I'm using a dynamic pass-through query in Access 2010 to retrieve one or more records from a back-end database. After much trial and error, I plagiarized enough of the right code to retrieve the appropriate records and assign them to unbound text-boxes on my datasheet form during an OnLoad event. The only problem remaining is in displaying multiple records. I've verified that I AM retrieving multiple records, but the contents of each record's fields overwrite the previous values stored to the form's textbox controls, so I always end up with just a single record displayed in my datasheet when I expect to see anywhere from one to 10.
I'm sure it's a simple solution. Can someone please point it out to me?
Private Sub Form_Load()
Dim sqlString As String
sqlString = "SELECT Transmitter_ID, Receiver_ID, UTC_Date, Local_Date from Detections"
If Not IsNull(Me.OpenArgs) Then
sqlString = sqlString & " where " & OpenArgs
End If
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As ADODB.Recordset
'Define and open connection
cnn.ConnectionString = "DRIVER={SQLite3 ODBC Driver};Database=z:\EWAMP\EWAMP_be_dev.sqlite"
cnn.Open
'Define ADO command
cmd.ActiveConnection = cnn
cmd.CommandText = sqlString
'Populate and enumerate through recordset
Set rst = cmd.Execute
If rst.EOF Then
MsgBox "Nothing found...", vbInformation + vbOKOnly
Exit Sub
Else
Do While Not rst.EOF
'// I'm guessing the problem is with my control assignments, here.
Me.cntl_Receiver_ID.Value = rst("Receiver_ID")
Me.cntl_Transmitter_ID.Value = rst("Transmitter_ID")
Me.cntl_UTC_Date.Value = rst("UTC_Date")
Me.cntl_Local_Date.Value = rst("Local_Date")
Debug.Print {Show me the four control values}
rst.MoveNext
Loop
End If
End Sub
Cheers!
DUHdley
I don't believe a form in Datasheet view can be used as an unbound form. But you can use the ADO recordset as the forms recordset.
Set Me.Recordset = rst
Then just be careful not to close your variable named rst until the form closes.
Another alternative solution is to use an in-memory, fabricated, disconnected ADO recordset. Basically, you'd end up creating a new recordset, append fields to it to match your existing recordset, and then move all the data into your new recordset. But I really don't see the point in doing this if you already have a valid, filled ADO recordset.
If you really need/want to display multiple records in an unbound form, I think you would have to use ActiveX controls such as the GridView, ListView, TreeView, or MSFlexGrid. I've noticed that most skilled, professional Access developers stay away from ActiveX controls as much as possible. If and when they do use them, they usually limit it to only the TreeView and the ListView, I think because they are about the only ActiveX controls that add enough value to be worth putting up with whatever problems they might introduce.
I suggest you take a look at this article concerning the differences between DAO and ADO.
http://www.utteraccess.com/wiki/index.php/Choosing_between_DAO_and_ADO
A reader in another forum pointed me to a solution similar to that posed by HK1, namely Set Me.Recordset = rst. That fixed my original problem, but created another.
First I re-bound my four textbox controls on the unbound form, and then modified the code significantly, using the sample from http://msdn.microsoft.com/en-us/library/ff835419.aspx. The revised code looks like this:
Private Sub Form_Load()
Dim sqlString As String
sqlString = "SELECT Transmitter_ID, Receiver_ID, UTC_Date, Local_Date from Detections"
If Not IsNull(Me.OpenArgs) Then
sqlString = sqlString & " where " & OpenArgs
End If
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Define and open connection
Set cn = New ADODB.Connection
cn.ConnectionString = "DRIVER={SQLite3 ODBC Driver};Database=z:\EWAMP\EWAMP_be_dev.sqlite;"
cn.Open
'Create an instance of the ADO Recordset class,
'and set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = sqlString
'// .LockType = adLockOptimistic
.LockType = adLockReadOnly
.CursorType = adOpenKeyset
'// .CursorType = adOpenStatic
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set cn = Nothing
Set rs = Nothing
End Sub
The form now display four rows for four returned records, 20 rows for twenty records, and on, up to at least 256k rows (as specified by my parameter set). The only remaining teeny tiny problem is that for four or more records, if I press the "last row" navigation button (>|), the local cursor sets focus to one or more of the intermediate rows, and the control's properties sheet refreshes vigorously (multiple times per second). If I have more form rows than can be displayed on the screen, I can not navigate or cursor to the last row. It's as though the record set is constantly being updated.
As you can see, I've played with the RecordSet LockType and CursorType properties (including adOpenDynamic and adOpenForwardOnly, both of which caused a run-time error with the Set Me.Recordset statement). Toggling the LockType between adLockOptimistic and AdLockReadOnly, and the CursorType between adOpenKeyset and adOpenStatic makes no difference in the retrieval performance (which is fantastically fast now!) or the apparent refresh rate (which is even faster, unfortunately).
Perhaps it's worth mentioning that the "Detections" table the sqlString "selects" from contains ~4M records. I was frustrated in my previous attempts to use a form with a data source bound to a passthrough query of this table, because the query always returned the entire 4M records to the client regardless of the filter/WhereClause/OpenArgs parameter I passed to the form. The solution shown above would be perfect if only I could close the connection (I've tried) or otherwise quiesce the RecordSet after I've invoked it once.

Resources