Binding a FormView to a DataSet - asp.net

Im forced to use ODBC, and i would like to bind a DataSet to a FormView. So far i have this code:
Sub lookup(data As String, city As String)
Dim query As String = "SELECT FIND_KORT_VEJ_FUL.STREET_NAME, FIND_KORT_VEJ_FUL.ZIPCODE, UXOR_CITY_DK.NAME AS cityName FROM UXOR_CITY_DK " & _
"Join(FIND_KORT_VEJ_FUL) " & _
"ON UXOR_CITY_DK.KOMMUNE_KODE=FIND_KORT_VEJ_FUL.MUNICIPALITY_CODE WHERE UXOR_CITY_DK.NAME = '" & city & "' " & _
"LIMIT 5"
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ODBCDataConnectionString").ConnectionString
Dim initialDataSet As New DataSet("initial")
Dim dt As DataSet = GetDataSetFromAdapter(initialDataSet, connectionString, query)
FormView1.DataSource = dt
FormView1.DataBind()
End Sub
Public Function GetDataSetFromAdapter(ByVal dataSet As DataSet, ByVal connectionString As String, ByVal queryString As String) As DataSet
Using connection As New OdbcConnection(connectionString)
Dim adapter As New OdbcDataAdapter(queryString, connection)
' Open the connection and fill the DataSet.
Try
connection.Open()
adapter.Fill(dataSet)
Catch ex As Exception
End Try
' The connection is automatically closed when the
' code exits the Using block.
End Using
Return dataSet
End Function
FormView:
<asp:FormView ID="FormView1" runat="server" EmptyDataText="Ingen data">
<ItemTemplate>
<table>
<tr>
<td>Postnummer: <%#Eval("MUNICIPALITY_CODE") %></td>
</tr>
<tr>
<td>Indbyggere: </td>
</tr>
<tr>
<td>Geografisk lokation: </td>
</tr>
<tr>
<td>Roskilde ligger i Roskilde kommune</td>
</tr>
<tr>
<td><br /><h3><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></h3></td>
</tr>
<tr>
<td>Borgmester: </td>
</tr>
<tr>
<td>Antal veje i kommunen: #</td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
I have verified the query and querystring, both work. The FormView does not get populated with the above code. Is it possible to bind a FormView to a DataSet? or is there a better method?

I've noticed a few things you probably need to change here. Here is your modified function below. The main issue is the connection not being closed. Regardless of what you may read elsewhere, SQL connections are not closed by the Using block. However, I am not sure about the OdbcConnection. I would recommend including the closing lines just in case.
Public Function GetDataSetFromAdapter(ByVal dataSet As DataSet, ByVal connectionString As String, ByVal queryString As String) As DataSet
Using connection As New OdbcConnection(connectionString)
Dim adapter As New OdbcDataAdapter(queryString, connection)
' Open the connection and fill the DataSet.
Try
connection.Open()
adapter.Fill(dataSet)
connection.Close()
Catch ex As Exception
connection.Close() 'This is necessary to avoid accidental multiple connections.
End Try
' The connection is automatically closed when the
' code exits the Using block.
End Using
Return dataSet
End Function
But the real problem I believe is that you are not referencing the table itself. Dataset only contains the tables, you must specify them when binding...
Sub lookup(data As String, city As String)
Dim query As String = "SELECT FIND_KORT_VEJ_FUL.STREET_NAME, FIND_KORT_VEJ_FUL.ZIPCODE, UXOR_CITY_DK.NAME AS cityName FROM UXOR_CITY_DK " & _
"Join(FIND_KORT_VEJ_FUL) " & _
"ON UXOR_CITY_DK.KOMMUNE_KODE=FIND_KORT_VEJ_FUL.MUNICIPALITY_CODE WHERE UXOR_CITY_DK.NAME = '" & city & "' " & _
"LIMIT 5"
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ODBCDataConnectionString").ConnectionString
Dim initialDataSet As New DataSet("initial")
Dim dt As DataSet = GetDataSetFromAdapter(initialDataSet, connectionString, query)
FormView1.DataSource = dt.Tables(0)
FormView1.DataBind()
End Sub

Related

VB.NET Connection string ADODB Connection (Web.Config)

I write the code below to connect database using web config but cannot connect database using ADODB to fetch data from database into textboxes
Webconfig
<connectionStrings>
<clear />
<add name="constr" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|CustomerInfor.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>
SearchButton
Dim consString As String = System.Configuration.ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim objConn As New OleDbConnection(consString)
objConn.Open()
Please help with right code to fetch data from database into textboxes
Thanks
Ok, lets try this a bit different.
First up: Lets get the connection string OUT side of the code.
Like for desktop, or anything else? You can add values like connection string to the project like this:
And really nice is you get to use the connection builder to do this.
The above setting are shoved into web.config for you automatic.
So, setup your connection in above.
Ok, now in this case, I just shove on the screen a few text boxes for a user and hotel name.
Real plane jane like this:
<div style="width:25%;text-align:right;padding:25px;border:solid;border-width:1px">
<style> .tbox {width:260px;margin-left:5px;margin-bottom:15px;border-radius:8px;border-width:1px}</style>
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" class="tbox"/>
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" class="tbox" />
<br />
Last Name:<asp:TextBox ID="txtLast" runat="server" class="tbox"/>
<br />
City: <asp:TextBox ID="txtCity" runat="server" class="tbox"/>
<br />
Active:<asp:CheckBox ID="ckActive" runat="server" />
<br />
<br />
Ok, now our code to load this. I don't have a text box or source for the id, but a integer value OR a text value will work.
So, our code to load up is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Dim cmdSQL As OleDbCommand = New OleDbCommand()
cmdSQL.CommandText = "SELECT * from tblhotels where ID = #ID"
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = 23
Dim rst As DataTable = MyRst(cmdSQL)
With rst.Rows(0)
txtHotelName.Text = .Item("HotelName")
txtFirst.Text = .Item("FirstName")
txtLast.Text = .Item("LastName")
txtCity.Text = .Item("City")
ckActive.Checked = .Item("Active")
End With
ViewState("rst") = rst
End Sub
Note the cute helper routine MyRst.
So, you can use that routine EVERY where. eg:
Dim cmdSQL As OleDbCommand = New OleDbCommand("select * from RoomTypes")
Dim rst as DataTable = MyRst(cmdSQL)
So, it just a handy dandy routine. (you do NOT have to use parameters if you don't need them).
Ok, so we loaded the one row into the table (and we save that row for later use into ViewState)
Ok, so now we see this:
Now, the save code. Note how we used a record set (datatable) in place of a GAZILLION parameters.
We do this for quite a few reasons.
Strong data type conversion occurs here.
Parameter order for the save does not matter. I can cut-paste, or add 5 or 15 more columns here, and it works - and order does not matter!!!
So, now the save code.
Protected Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
SaveData()
End Sub
Sub SaveData()
Dim rst As DataTable = ViewState("rst")
Using con As New OleDbConnection(My.Settings.AccessTest2)
Using cmdSQL As New OleDbCommand("SELECT * from tblHotels WHERE ID = 0", con)
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmdSQL)
Dim daSQLU As OleDbCommandBuilder = New OleDbCommandBuilder(da)
con.Open()
With rst.Rows(0)
.Item("HotelName") = txtHotelName.Text
.Item("FirstName") = txtFirst.Text
.Item("LastName") = txtLast.Text
.Item("City") = txtCity.Text
.Item("Active") = ckActive.Checked
End With
da.Update(rst)
End Using
End Using
End Sub
NOTE: not a bug, I MOST certainly did use where ID = 0
So, the nice part is we can add more text box etc. We will have to add code to setup the text boxes, but at least the order don't matter.
Last but not least?
That helper routine, the one I use to fill datatables. I even use it for say filling out combo box (dropdown lists), or whatever.
Public Function MyRst(cmdSQL As OleDbCommand) As DataTable
Dim rstData As New DataTable
Using MyCon As New OleDbConnection(My.Settings.AccessTest2)
cmdSQL.Connection = MyCon
MyCon.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
Return rstData
End Function
So note how we used the connection string setting that we setup in the project.
And since access is sensitive to parameter order, then I adopted the above idea of using a data table. Note that this approach also works for a grid, or even adding rows. When you run that update routine? rows added, rows edits, row deleted?
They all are done for you with the ONE da.Upate(rst).
Note also, you should set your project to run as x86, and not x64, since JET ONLY can work as x32. However, the ACE data engine can be had for x64 bits.

Transfer Excel data into a SQL Server table using file upload

I need to give user a functionality of file upload where user can browse for a file and upload it to server. Data stored in the file will be extracted and inserted into a table.
Frontend code:
<asp:Panel ID="panelFileUpload" runat="server">
<table>
<tr>
<td><asp:Label ID="lblFileUpload" runat="server" Text="File Upload:"></asp:Label></td>
<td><asp:FileUpload CssClass = "FileUpload" ID="fuFileUpload" runat="server" />
<asp:Button ID="btnUploadFile" runat="server" CssClass="inputButton" OnClientClick="fnStartInterval()" Text="Upload" ValidationGroup="A" />
<asp:RequiredFieldValidator ID="RFValidator" runat="server" ControlToValidate="fuFileUpload" Font-Italic="True" Display="Dynamic" ValidationGroup="A">*Please choose a file to upload! </asp:RequiredFieldValidator>
</td>
</tr>
</table>
</asp:Panel>
I found this backend code for file upload but this is not working. My Excel file has 4 cols - col1...col4. I am not sure how to map the column of Excel to table structure.
Backend code:
Protected Sub btnUploadFile_Click(sender As Object, e As EventArgs) Handles btnUploadFile.Click
Dim filename As String = Path.GetFileName(fuFileUpload.PostedFile.FileName)
Dim contentType As String = fuFileUpload.PostedFile.ContentType
Using fs As Stream = fuFileUpload.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Integer))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = "INSERT INTO dbo..table_1 VALUES (#ContentType, #Data)"
Using cmd As New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = contentType
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
End Sub
Here, contenttype is being directly read from file. is there a way to read all 4 columns as it is and store it in table.
No promises on this but it should give you an idea on how this can be accomplished.
The DataTable is agnostic when it comes to its source so you can use the same DataTable for both the retrieved data from Excel and the insert data from to Sql Server.
Private Sub UpdateSQLServerFromExcel(FilePath As String)
Dim dt = New DataTable()
Using cnSource As New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FilePath};Extended Properties=""Excel 12.0 Xml;HDR=YES"";")
Using selectCommand As New OleDbCommand("Select * From [Sheet1$];", cnSource)
Using da As New OleDbDataAdapter
'The following allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method)
da.AcceptChangesDuringFill = False
da.Fill(dt)
End Using
End Using
End Using
Using cnDestination As New SqlConnection("Your Sql Server connection string")
Using selectCommand As New SqlCommand("Select * From YourSqlTableName;", cnDestination)
Using da As New SqlDataAdapter()
da.SelectCommand = selectCommand
Dim cb As New SqlCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
End Sub

Send email to multiple users from listview

I want to get users email id in listview and whatever email generated by listview according to query. Now on send click I want all email id generated by listview to get that email.
I know how to bind listview but how can I get email to send mail?
Private Sub BindListView()
Dim constr As String = ConfigurationManager.ConnectionStrings("conio2").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT email FROM users where city = 'new york' order by ID asc"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
emailList.DataSource = dt
emailList.DataBind()
End Using
End Using
End Using
End Sub
Suppose if you have ListView defined as below in the HTML part:
<asp:ListView ID="emailList" runat="server" ConvertEmptyStringToNull="False">
<ItemTemplate>
<asp:Label Text='<%# Eval("Email") %>' runat="server" ID="lblEmail"></asp:Label>
</ItemTemplate>
</asp:ListView>
You can enumerate over all the ListViewItems, get the Email IDs from the Label, and join it into a string str separated by comma (,) which can then be directly utilized for sending the email to multiple recipients.
Dim str As String = ""
For Each li As ListViewItem In emailList.Items
Dim lbl As Label = CType(li.FindControl("lblEmail"), Label)
If lbl.Text <> "" Then
str = str + lbl.Text + ","
End If
Next
str = str.Substring(0, str.Length - 1)
Use str within the message sending code as message.cc.Add(str)
where message is the object of System.Net.Mail.MailMessage
From what I understand you have some function (or sub), that sends e-mails and you just need to provide data to that function.
For simplicity let's name this:
Private Sub SendEmail(address as string, title as string, body as string)
I have also added two TextBoxes:
TextBoxTitle for holding e-mail title and
TextBoxBody for holding e-mail body
Here's the code:
Private Sub SendEmail_Click(sender As Object, e As EventArgs) Handles SendEmail.Click
For Each item As ListViewItem In emailList.Items
SendEmail(item.SubItems.Item(0).Text, TextBoxTitle.Text, TextBoxBody.Text)
Next
End Sub

Trouble passing results from DataReader to textbox

I am making an admin section that will allow access to several small SQL tables in my project.
I have repeaters set up to show my lists with a button to bring up a Modal for adding a new entry or editing an existing one. The code behind stores a value from the selected row, and then I would like to query my SQL Class to return a value to fill my text boxes. The code works back to the SQL Class and I can display a message box and get the proper results. I can't however get it to pass the value if the query back to the VB page to fill the text boxes.
Here is the Repeater
<%--Employee Repeater--%>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table class="display" id ="employeeList">
<thead>
<tr>
<th>
Name
</th>
<th>
Email
</th>
<th>
Update
</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("name")%>
</td>
<td>
<%# Eval("email")%>
</td>
<td>
<asp:Button ID="cmdEditName" runat="server" Text="Edit/Delete" CommandArgument= '<%#Databinder.Eval(Container.DataItem, "id")%>' OnClick="EditName"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
My Code Behind
'Open Name Modal bound to repeater
Public Sub EditName(ByVal sender As Object, ByVal e As System.EventArgs)
Dim wLink As New Button
Edit = True
wLink = DirectCast(sender, Button)
txtEditId.Text = wLink.CommandArgument
SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditName.Text = results
SQL.RunReader("SELECT email from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditEmail.Text = results
ModalName.Show()
End Sub
And the code in my SQL Class
Public Function RunReader(ByVal Query As String) As String
Dim results As String = ""
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
Dim R As SqlDataReader = SQLCmd.ExecuteReader
While R.Read
results = (R(0))
'MsgBox is just to show that I am getting results
MsgBox(results)
End While
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
Dim results = SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")
txtEditName.Text = results
Complete the runreader function with return statement
Public Function RunReader(ByVal Query As String) As String
Dim results As String = ""
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
Dim R As SqlDataReader = SQLCmd.ExecuteReader
While R.Read
results = (R(0))
'MsgBox is just to show that I am getting results
MsgBox(results)
End While
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
Return results
End Function
Then call this method as
Dim results = SQL.RunReader("SELECT name from Admin_Contacts WHERE Admin_Contacts.id = '" & txtEditId.Text & "' ")

How to declare a datasource in VB.NET?

I wrote an ASPX file in VB.NET. Originally this file ran successfully but after adding one additional parameter it now fails on "Name 'peType' is not declared".
This error does not make sense to me though because I have similar parameter, 'dType', which it does not error on. What is the cause of this error?
Here is some of my ASPX code file:
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
Dim TheMonthDate As Date = DateAdd(DateInterval.Month, -1, Today)
calStartDate.SelectedDate = CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy")
calEndDate.SelectedDate = GlobalFunctions.GlobalF.MonthLastDate(CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy"))
Dim arrType as New ArrayList()
Dim arrOrgUnit as New ArrayList()
Dim arrPEType as New ArrayList()
Dim peType As ListBox
arrType.Add("Product and Process")
arrType.Add("Product")
arrType.Add("Process")
dType.DataSource = arrType
dType.DataBind()
arrPEType.Add("-INC")
arrPEType.Add("-NC")
arrPEType.Add("-QC")
peType.DataSource = arrPEType
'peType.DataTextField = "DisplayColumnName"
'peType.DataValueField = "ValueColumnName"
peType.DataBind()
...
Dim TheType as String
Dim TheOrgUnit as String
Dim PE_Type as String
Select Case dType.SelectedValue
Case "Product and Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP' Or (SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
Case "Product":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PRODUCT_QXP')"
Case "Process":
TheType = "((SMARTSOLVE.V_QXP_ALL_EXCEPTION.QXP_BASE_EXCEPTION)='PXP_PROCESS_QXP')"
End Select
Select Case peType.SelectedValue
Case "INC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='INC'"
Case "NC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='NC'"
Case "QC":
PE_Type = "substring(a.QXP_EXCEPTION_NO, charindex('-', a.QXP_EXCEPTION_NO)+1, 4)='QC'"
End Select
...
<td>
Product Exception Type:
</td>
<td>
<ASP:DROPDOWNLIST ID="peType" RUNAT="Server" AUTOPOSTBACK="true" />
</td>
But now my error is:
Object reference not set to an instance of an object
You missed setting the DataTextField and DataValueField property, when you tried to bind DataSource to your Dropdownlist, so set as follows:
peType.DataSource = arrPEType
peType.DataTextField = "DisplayColumnName"
peType.DataValueField = "ValueColumnName"
peType.DataBind()

Resources