Send email to multiple users from listview - asp.net

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

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.

Visual Basic ASP.NET 4 Request.Form()

this may sound like a silly question but i am learning Visual Basic ASP.NET 4 and i have been asked to create a DropDownList which obtains information from a table using SQL. I cant seem to pull the selected item from the dropdownlist and show it on the screen using Request.Form.
I have tried this..
Dim selItem As String = Request.Form("DDList")
Response.Write(selItem)
but this does not show anything on screen. Please help as i am struggling with this.
I have added my dropdownlist as follows:
<asp:DropDownList ID="DDList" runat="server" Width="201px">
</asp:DropDownList>
<asp:DropDownList ID="DDList2" runat="server" Width="145px">
</asp:DropDownList>
My Class/Function
Public Class sqlFunc
Public Shared Function tableData() As DataSet
Dim oraConnect As New OracleConnection
oraConnect.ConnectionString = ConfigurationManager.ConnectionStrings("smart_dev").ConnectionString
Dim oraCommand As New OracleCommand
oraCommand.Connection = oraConnect
oraCommand.CommandType = Data.CommandType.Text
Dim lsSQL As String = ""
lsSQL = "SELECT code, description FROM ref_code WHERE domain = 'SPECIALTY'"
oraCommand.CommandText = lsSQL
Dim da As New OracleDataAdapter(oraCommand)
Dim ds As New DataSet
da.Fill(ds)
Return ds
End Function
What i am using on my .aspx.vb page;
Dim dsData1 As New DataSet
dsData1 = tableData()
DDList.DataSource = dsData1
DDList.DataValueField = "code"
DDList.DataTextField = "description"
DDList.DataBind()
DDList.Items.Insert(0, New ListItem(String.Empty, String.Empty))
DDList.SelectedIndex = 0
You don't need to get the selected value using Request.Form if you are using an asp:DropDown ASP.net control. All you have to do is:
Dim selItem As String = DDList.SelectedValue
Response.Write(selItem)
If you really want to use Request.Form, do it like this:
Dim selItem As String = Request.Form(DDList.ClientID)
Response.Write(selItem)
Also, make sure you have ViewState enabled and that you do not rebind the DropDown at PageLoad when there is a PostBack:
Sub Page_Load
If Not IsPostBack
' Bind your DropDown here
End If
End Sub

Passing value through path using postback url

I am using a datalist on customer page to list all customers. There is a page named "view" where I want to show the details of the particular selected customer. Here is the image button code:
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageURL(Eval("image")) %>' PostBackUrl='<%# Eval("id", "view.aspx?id={0}") %>'/></tr>
id is the unique field of the customer table. Now how should I retrieve the customer data on view.aspx, using the particular ID passed from the customer page. I use this code but it's not working:
Dim mycommand As New SqlCommand("SELECT * FROM customer where id = #id", con)
Int(ID = Request.QueryString("id"))
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
I just want to do that. In the customer page all customers are displayed with their image and when I click on any one of them then the details of the particular customer should be displayed on view.aspx page ..
you are using #id as CommandParameter to add this id as value to command parameter..
as
Dim mycommand As New SqlCommand("SELECT * FROM customer where id = #id", con)
mycommand.Parameters.Add("#id", SqlDbType.Int)
mycommand.Parameters("#id").Value = Convert.ToInt32( Request.QueryString("id"))
con.Open()
ProfileData.DataSource = mycommand.ExecuteReader
ProfileData.DataBind()
con.Close()
check these link to know about the parameter..
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
http://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.80%29.aspx

how do i display the "On Offer" indicator when the product is on offer in the database of asp.net?

I need to display the "on Offer" indicator next to the product in the gridview if the product has a number "1" in the "Offered" column in the database. if it is zero, then don't display. is there some way to achieve that? thanks.
In my product listing page:
Dim objCat As New Category
Dim objProduct As New Product
Dim i As Integer
Dim boolError As Boolean = False
objCat.ID = CType(Request.QueryString("CatID"), Integer)
' get details of the category
objCat.GetDetails()
' Display the category name
lblCatName.Text = objCat.Name
lblCatName2.Text = objCat.Name
' Display the category description
lblCatDesc.Text = objCat.Description
objCat.GetOfferedProducts()
For i = 0 To gvProduct.Rows.Count - 1
' Get the ProductId from the first cell
objProduct.ID = gvProduct.Rows(i).Cells(0).Text
Dim lblOffer As Label
lblOffer = CType(gvProduct.Rows(i).FindControl("lblOffer"), Label)
If objCat.Offered = "1" Then
lblOffer.Visible = True
Else
lblOffer.Visible = False
End If
Next
gvProduct.DataSource = objCat.GetProducts()
gvProduct.DataBind()
in my category class:
Public Sub GetOfferedProducts()
' Define a conection to database
' Read connection string from the web.config file.
Dim strConn As String
strConn = ConfigurationManager.ConnectionStrings("AppDb").ToString
Dim conn As New SqlConnection(strConn)
' Retrieve details of a given Category ID from the database
Dim strSql As String
strSql = "SELECT * FROM CatProduct cp INNER JOIN Product p " & _
"ON cp.ProductID=p.ProductID INNER JOIN Category c ON cp.CategoryID=c.CategoryID " & _
"WHERE cp.CategoryID=#CategoryID"
' Define an Command object to execute the SQL statement
Dim cmd As New SqlCommand(strSql, conn)
' Add parameter to the SQL command
cmd.Parameters.AddWithValue("#CategoryID", ID)
' Define a data adapter to fetch data
Dim da As New SqlDataAdapter(cmd)
' Define a data set to hold the data fetched
Dim ds As New DataSet
' Open database connection
conn.Open()
da.Fill(ds, "CatProduct")
' Close the database connection
conn.Close()
If ds.Tables("CatProduct").Rows.Count <> 0 Then
Name = ds.Tables("CatProduct").Rows(0)("CatName")
Description = ds.Tables("CatProduct").Rows(0)("CatDesc")
ImageFile = ds.Tables("CatProduct").Rows(0)("CatImage")
Offered = CType(ds.Tables("CatProduct").Rows(0)("Offered"), Integer)
End If
I would hook up the gridview's OnRowDataBound in your aspx page:
<asp:gridview id="MyGridView"
autogeneratecolumns="true"
allowpaging="true"
onrowdatabound="MyGridView_RowDataBound"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="lblOffer"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Then in the code behind you could do something like this:
void MyGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var lbl = e.Row.FindControl("lblOffer");
If objCat.Offered = "1" Then
lbl.Visible = True
Else
lbl.Visible = False
End If
}
}
Hope that helps!!
There are various ways to make this happen. Basically, you're just looking to conditionally show/hide an element in the grid.
Which of the many ways to do this happens to be the best way entirely depends on how you're retrieving, binding to and displaying your data. You can put the logic in the business layer (a certain property is set or null based on business rules, etc.), in your data binding code (if you're looping through records for the display or something, such as in an ItemDataBound handler), in your display code (if you're just declaring everything in the aspx and just need to toss in an Eval and a conditional), etc.

ASP.NET DropDownList posting ""

I am using ASP.NET forms version 3.5 in VB
I have a dropdownlist that is filled with data from a DB with a list of countries
The code for the dropdown list is
<label class="ob_label">
<asp:DropDownList ID="lstCountry" runat="server" CssClass="ob_forminput">
</asp:DropDownList>
Country*</label>
And the code that the list is
Dim selectSQL As String = "exec dbo.*******************"
' Define the ADO.NET objects.
Dim con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
' For each item, add the author name to the displayed
' list box text, and store the unique ID in the Value property.
Do While reader.Read()
Dim newItem As New ListItem()
newItem.Text = reader("AllSites_Countries_Name")
newItem.Value = reader("AllSites_Countries_Id")
CType(LoginViewCart.FindControl("lstCountry"), DropDownList).Items.Add(newItem)
Loop
reader.Close()
CType(LoginViewCart.FindControl("lstCountry"), DropDownList).SelectedValue = 182
Catch Err As Exception
Response.Redirect("~/error-on-page/")
MailSender.SendMailMessage("*********************", "", "", OrangeBoxSiteId.SiteName & " Error Catcher", "<p>Error in sub FillCountry</p><p>Error on page:" & HttpContext.Current.Request.Url.AbsoluteUri & "</p><p>Error details: " & Err.Message & "</p>")
Response.Redirect("~/error-on-page/")
Finally
con.Close()
End Try
When the form is submitted an error occurs which says that the string "" cannot be converted to the datatype integer. For some reason the dropdownlist is posting "" rather than the value for the selected country.
2 things I can think of.
1) Are you sure the SQL is returning something that has the value of 182 ?
2) Are you rebuilding the Drop-down list on Postback ? as it's dynamic you'll have too else it won't know which value you selected.

Resources