asp.net vb listview concatenate data items in code behind - asp.net

I have a listview with some data bound to it.
In this data are column for an address.
How would I go about accessing these data items in code behind so I can concatenate them into one easy variable and miss out columns that have no data in, i have fields:
address
address1
town
county
postcode
I don't have a problem with the concatenation just accessing the data items.
Thanks J.
UPDATED
I am getting data out via a dataset and binding it to a listview.
Is it possible to access data items in the code behind to format or do whatever i want with them then showing it in the list view such as, concatenating the address fields into one variable?
so instead of writing:
DataBinder.Eval(Container.DataItem, "address") & ", " & DataBinder.Eval(Container.DataItem, "address1") & ", " & DataBinder.Eval(Container.DataItem, "town") etc...
in the actual list view i could do this in the code behind in a string variable then show the variable in the list view?
'select command
Dim cmdSchedule As SqlCommand = New SqlCommand()
cmdSchedule.Connection = keypadSQL
cmdSchedule.CommandText = "spSchedule"
cmdSchedule.CommandType = CommandType.StoredProcedure
'data adapter
Dim daSchedule As SqlDataAdapter = New SqlDataAdapter
daSchedule.SelectCommand = cmdSchedule
'data set
Dim dsSchedule As DataSet = New DataSet()
daSchedule.Fill(dsSchedule, "Schedule")
lvSchedule.DataSource = dsSchedule
lvSchedule.DataBind()
cmdSchedule.Dispose()

First put your items into accessible controls in the ListView, such as a label or literal.
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text="<%= Eval("address") %>" />
</ItemTemplate>
</asp:ListView>
Then you can loop through the items and using FindControl, pull each string out individually.
Dim items As List(Of ListViewDataItem) = ListView1.Items
For Each item As ListViewDataItem In items
Dim strAddress As String = CType(item.FindControl("lblAddress"), Label).Text
Next
UPDATED
I'd think the best way would be to format it in SQL Stored Procedure and return it as a new field. Something like this:
SELECT *, address + ', ' + address1 + ', ' + town ', ' + county + ', ' postcode AS fullAddress
FROM ...
Then you'd just have to use <%= DataBinder.Eval(Container.DataItem, "fullAddress") %> to get the formatted address. You could even format it with HTML in the SP as long as you're weary of potential injection attacks (not sure of the original address input method).

Related

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

How do I delete specific row of records on gridview?

again.
On the gridview markup, I have these:
<asp:TemplateField HeaderText="Dates">
<ItemTemplate>
<asp:Label ID="dates_label runat="server" Text='<%# Bind("shipDates","{0:M/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="ehide" Value='<%# Eval("eventId") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
The gridview displays several rows of records and using hidden form field, I am able to associate a row with its specific eventid from the events table.
Then below is the codebehind that attempts to delete each row of records.
For Each row As GridViewRow In GridView1.Rows
Dim dates_label = DirectCast(row.FindControl("dates_label"), Label)
Dim shipDates = Date.ParseExact(dates_label.Value, "M/dd/yyyy", Nothing)
Dim ehide = DirectCast(row.FindControl("ehide"), HiddenField)
Dim eventid = ehide.Value
Dim myConnectionString As [String] = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim myConnection As New SqlConnection(myConnectionString)
Try
myConnection.Open()
strSQL = "Delete from tblEvents where username=#UserName and eventid = #eventid"
com = New SqlCommand(strSQL, myConnection)
com.Parameters.AddWithValue("#username", Session("username"))
com.Parameters.AddWithValue("#eventid", eventid)
Response.Write(strSQL)
Response.End()
com.ExecuteNonQuery()
myConnection.Close()
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Information Saved successfully')</SCRIPT>")
Response.Redirect("~/default.aspx")
Catch ex As SqlException
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('" + ex.Message + "')</SCRIPT>")
Finally
myConnection.Close()
End Try
Next
When I run a debugger on this sub, it attempts to delete any row with the first eventid.
For instance, assume that there are 5 row of records on the event table and the eventIDs are 1,2,3,4,5. These are made up numbers for brevity.
If I try to delete the first record with eventId 1, I get:
delete from tblEvents where eventId = 1
If I try to delete the row with eventId 5, I still get:
Delete from tblEvents where eventId = 1
How do I resolve this in such that each row gets deleted by its rowId?
Thanks in advance.
Assumptions based on our discussion.
You have a gridview that has row selection enabled
You also have Delete Rows enabled. (EDIT: Just rememberd this option won't be available until you place the delete command in the SqlDataSource control)
That eventid is coming from a database
If this is all true then deleteing rows is ridiculously easy:
Place the eventid in GridView1 DataKeyNames via the Property page.
From the designer select the SqlDataSource control connected to GridView1
In the SqlDataSource Property List
a. find DeleteQuery and select it's (Query)
b. This will open the Command and Parameter Editor dialog box
DELETE command: "DELETE FROM tblEvents WHERE (username = #UserName) AND (eventid = #eventid)
click the Refresh Parameters button in the dialog
Username: Parameter Source is Session, with SessionField as appropriate
eventid: Parameter Source is Control, with ControlID of GridView1
Save it all
Now the Delete command is "wired" to your primary key (eventid) and delete should just work

Combine Multiple Data Sources to a Single ASP.NET Repeater?

I have a repeater like so:
<asp:Repeater ID="rptrRooms" runat="server" OnItemCommand="Choose_Room">
<ItemTemplate>
<asp:Button ID="btnChooseRoom" runat="server"
CommandName="<%# Container.DataItem.ToString %>" Text="<%# Container.DataItem %>"
/>
</ItemTemplate>
</asp:Repeater>
I bind a data source to the repeater like so:
Dim dbRooms As New pbu_housingEntities
Dim gender As String = Session("gender").ToString
Dim hall As String = CStr(Session("hall"))
Dim selectedRooms = (From sh In dbRooms.Rooms _
Where sh.gender = gender _
Where sh.current_occupancy < sh.max_occupancy _
Where sh.is_available = True _
Where sh.building_name = hall _
Select sh.room1
)
rptrRooms.DataSource = selectedRooms
rptrRooms.DataBind()
Problem is, I also want to show the viewer the available number of spots in the room. But this requires somehow pull in either the current_occupancy / max_occupancy or in performing a calculation (e.g. max_occupancy - current_occupancy = actual_available) and then returning that with the room.
The end result I'm looking for is to return each room in a button control with text that looks like this:
"Room 1 - 2 Open" "Room 8 - 1 Open" and so on
Thanks davemackey :) Something like this.
Select New With {sh.room1, .actual_available = sh.max_occupancy - sh.current_occupancy}
Amit_g's comment above was the key. I needed to put into the select statement actual_available = sh.max_occupancy - sh.current_occupancy. If Amit posts an answer, I'll change the "correct" answer over to Amit to give you the credit for the answer. :)

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.

Adding Column Value Dynamically to a DataGridview

I have three column in my datagridview .One is text ,one is Combo and another one is Text ...i don't want to use datasource want to add values on cell like datagridview.Rows[].cells[].value. Help me how i can do it? My database have several columns...How to add column value dynamically....
I just had to do the same exact type of thing...here is how you add a column.
If Not IsPostBack Then <br>
Dim field As New TemplateField
field.HeaderText = "Name of Column"
Dim col As DataControlField = field
GridView.Columns.Add(col)
End If
**In the Gridview_rowcreated Sub
e.row.cells(cellnumber from 0 to N).controls.Add(data)
you're going to have to create a connection and a connection string
here is an example...
Dim Dbconn As SqlConnection
Dim Dbcmd As SqlCommand
Dbcmd = New Data.SqlClient.SqlCommand()
Dbcmd.Connection = Dbconn
Dbcmd.CommandType = Data.CommandType.Text
Dbcmd.Commandtext = "select * from table"
dbconn.open()
//then you need a data reader
dim dr as sqlclient.sqldatareader
dr = dbcmd.executereader
while dr.read
add each item to a list
end while
then on page load set your datasource of the grid to the list
hope this helps...if you have any questions just ask me.
I would highly recommend to use a Repeater instead of datagridview and render as many columns as you want.
.aspx code
<tr>
<asp:Repeater ID="rptDayHeaders" runat="server">
<ItemTemplate>
<td>
<strong><asp:Literal ID="ltMonthHeader" runat="server"></asp:Literal></strong>
</td>
</ItemTemplate>
</asp:Repeater>
</tr>
.aspx.vb code
rptDayHeaders.DataSource = daysList
rptDayHeaders.DataBind()
where dayslist needs to be an array of the number of columns you want.
We have used the same approach to generate a complete Gantt Chart
Try something along the lines of
dataGrid.Rows.Add(new object[] { "value1", 42, "value3"});

Resources