Dataset in asp.net - 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.

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.

Get child page data from master page selectedItems

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.

User details stored in separate table ASP.NET Identity

I am a complete beginner at ASP.net(and this forum) i am using Visual studio 2013 and have created created another table in the created database using the package manager console.
How do i go about placing the information into this new table? (I am looking to store firstname and last name in a separate table)
The create account button is below:
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = UserNameCtrl.Text
Dim Firstnane As String = firstnamectrl.Text
Dim manager = New UserManager
Dim User = New ApplicationUser() With {.UserName = userName}
Dim result = manager.Create(User, Password.Text)
If result.Succeeded Then
IdentityHelper.SignIn(manager, User, isPersistent:=False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
Any pointers in the right direction, hints or suggested reading would be very helpful.
If I understand correctly, this link may be of some help:
http://www.codeguru.com/vb/gen/vb_database/adonet/article.php/c15033/A-Basic-VBNET-ADONET-Tutorial-Adding-Deleting-and-Updating.htm
It is for a windows form application, but it should translate pretty well if you're using web forms. Basically, you just want to make a connection to the database during the button click event (the simplest way I know of to make this connection is using ADO.NET), and pass the values of the first and last name in a SQL query to the sql server.
You would be building the sql query as a string, and concatenating your vb variables into that string. Something like; "Insert into table xxx(firstname, LastName) values " & Firstname & ", " & Lastname...

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.

Send Email based on Dropdownlist.SelectedItem & Also Insert the Dropdownlist.SelectedValue into Database

I don't know how to go about this. I have a web form with dropdown list, named Recruiter. I have two SQL tables named Perm_Commision_Lookup & UserList.
One of the tables contain email and the other does not. The Perm_Commision_Lookup table does not contain recruiter's email, so I decided to Inner Join it with UserList table which contain recruiter emails. The LookupValue (Recruiter's display name) column from the Perm_Commision_Lookup table is what's displayed to the end user and the pk_LookupID column is the one that's inserted into the database.
What I want to achieve is this: When a user select let's say "John Doe" from the Recruiter dropdown list, I want to send out an email to John Doe alerting him that a form has been submitted and at the same time insert the selected value (pk_LookupID) into the database.
I see that the dropdown list has two field named: DataTextField="LookupValue" and DataValueField="pk_LookupID but how to get the User_Email is my major problem. Below is my SQL select...So far I can do a SQL INNER JOIN...which shown below and also I can display multiple columns into dropdown list...I'm also trying SQLDataReader but I'm just stop with how to get it done.
SELECT Perm_Commision_Lookup.pk_LookupID, Perm_Commision_Lookup.LookupValue, UserList.User_Email
FROM Perm_Commision_Lookup
INNER JOIN UserList ON Perm_Commision_Lookup.LookupUserName = UserList.GM_Username
Any help will be appreciated...
Thanks for your reply! Correct! It's linked via LookupUserName. That's what I have as for now...but still have the problem
Public Sub BindDropDownListData()
' connection string
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using mySqlConnection As New SqlConnection(connectionString)
Try
' open the Sql connection
mySqlConnection.Open()
' Sql Command query to retrieve pk_LookupID, LookupValue, GM_Username, User_Email
Dim mySqlCommand As New SqlCommand(" SELECT Perm_Commision_Lookup.pk_LookupID, Perm_Commision_Lookup.LookupValue, UserList.GM_Username, UserList.User_Email FROM Perm_Commision_Lookup INNER JOIN UserList ON Perm_Commision_Lookup.LookupUserName = UserList.GM_Username order by LookupValue asc", mySqlConnection)
Dim mySqlDataAdapter As New SqlDataAdapter()
mySqlDataAdapter.SelectCommand = mySqlCommand
Dim myDataSet As New DataSet
' mySqlConnection.Open()
' Sql Data Reader to fetch the records row by row in forward direction.
Dim myDataReader As SqlDataReader = mySqlCommand.ExecuteReader()
'Perm_Commision_Lookup
If myDataReader.HasRows Then
' read each row fetched using DataReader
While myDataReader.Read()
Dim li As New ListItem()
'email = myDataReader("User_Email")
li.Value = myDataReader("pk_LookupID")
li.Text = myDataReader("LookupValue")
DropDownList1.Items.Add(li)
End While
End If
myDataReader.Close()
Catch ex As Exception
Label1.Text = ex.Message
Finally
' close the Sql Connection
mySqlConnection.Close()
End Try
DropDownList1.Items.Insert(0, New ListItem("Please Select Recruiter", ""))
End Using
End Sub
1: Use dropdown selectedIndexChanged event.
2: Inside the handler query the database to get the Email and send email.
3: You can selected lookupname from dropdown in the SelectedIndexChanged handler like myddl.SelectedItem.Text or you can get lookupid like myddl.SelectedValue.
From your query it seems your tables are linked via LookupUserName correct or is it LookupId?
And this might help.

Resources