Designing notification sections in asp.net - asp.net

I am trying to design a notification section for my ASP.NET website.
My requirement is similar to this image layout.
I was able to implement this with the asp repeater control and binding it with database.
I have table in my DB that has image, name and comments as its columns.
So according to the no. of rows in the DB table, the repeater control will get me the contents in the defined layout.
But i also wanted to implement the close button ("X" - top right corner). this close button will just remove the particular comment (but it will not delete data in DB).
Could you please help me in achieving this ??
Also thanks to suggest any other possible option to acheive this.
PFB the code i have done so far
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td style="height:64px;width:64px">
<asp:Image ID="imgEmployee" CssClass="imgClass" ImageUrl='<%# Eval("ImagePath")%>'runat="server" />
</td>
<td>
<asp:Label runat="server" Text='<%# Eval("Name")%>'></asp:Label>
<p> <%# Eval("Comments")%></p>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
and code behind
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetData();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
private DataSet GetData()
{
string CS = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from tblNotification", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
And my table (tblNotification) has 3 columns - "ImagePath", "Name" and "Comments"

Related

How to Redirect to new asp page while clicking on the data row of the data grid view in asp.net

My data grid view in asp.net displays only selected id from sql server database as a single row.
Now I need to display a particular page when I click on the particular id (data row) and also I want to display all the details in a new page belongs to the selected id (on click on the id).
I have tried this code:
protected void btnserch_Click(object sender, EventArgs e)
{
SqlConnection objsqlconnection = new SqlConnection(CONNECTIONSTRING);
string query = "Select id from registration";
SqlCommand objsqlcommand = new SqlCommand(query, objsqlconnection);
objsqlconnection.Open();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds=new DataSet();
objsqlcommand.CommandText = query;
objsqlcommand.Connection = objsqlconnection;
da = new SqlDataAdapter(objsqlcommand);
da.Fill(ds);
objsqlcommand.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
objsqlconnection.Close();
}
This code returns a grid by selecting only id column from registration table. Now when I click on the data row of the id column, I need an another page which should display all the details belonging to that id.
like #MelanciaUK said "OnItemDataBound" is your friend.
For checking ID even on postback, select it in "SelectedIndexChanging"
hope it helps.
Easiest way to redirect to new page:
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="ID">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Name">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Edit">
<ItemTemplate>
<a href='Newpage.aspx?ID=<%#Eval("ID")%>'>Edit</a>
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
You can redirect from one page another page in two ways
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="Action">
<ItemTemplate>
<a href='mypage.aspx?ID=<%#Eval("RowID")%>'>Edit</a>
Edit
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
<script type="text/javascript">
function Redirect(id) {
window.location = 'mypage.aspx?ID=' + id;
}
</script>

Take parameter from listview

i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.

Add rows to a table dynamically

At the moment I am trying to create a table whose content is supposed to be created by a subclass (result of querying a RESTful web service). I have been working for quite some time on that now and I just cannot seem to get it to work. I have tried so many different solutions.
creating the table in the subclass and add it to Page.Controls. That gets me "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)." which does not make sense at all.
I have tried to create an empty table on the page and passed its handle to the subclass which was responsible for adding rows. Noting happened.
I have tried to return a TableRowCollection and assigned it to the previously created (empty) table. Nothing happened.
Now I just want to add one row and one cell to the table (baby steps towards what I need). Not even that works. Please find the code for that attached:
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cell = new TableCell();
row.Cells.Add(cell);
cell.Controls.Add(new TextBox());
The table is simple and empty:
<asp:Table ID="table" runat="server" />
The source code that is displayed by my browser looks like that:
<table id="table">
</table>
I have been looking at countless examples on the web and all look like this. I guess it is only a tiny problem somewhere but I have not been able to figure it out. Now I am willing to offer life-long gratitude to everybody who can provide the hint for solving this mess.
It is working, I have tested it:
In my page load, I have:
protected void Page_Load(object sender, EventArgs e)
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.Controls.Add(new TextBox());
row.Cells.Add(cell);
table.Rows.Add(row);
}
On my aspx page, I have:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Table ID="table" runat="server" />
</asp:Content>
The html rendered by this code:
<table id="MainContent_table">
<tbody><tr>
<td><input name="ctl00$MainContent$ctl00" type="text"></td>
</tr>
</tbody></table>
I would use either an asp:GridView or an asp:Repeater
eg with Repeater
<table>
<asp:Repeater id="repeater1" runat="server">
<ItemTemplate>
<tr>
<td><asp:Literal id="literal1" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
then in your code behind
repeater1.DataSource = myDatasource;
repeater1.DataBind();
or you could use a GridView
using table.Rows.Add() will tend to cause you problems, particularly with disappearing content on postback, or problems with event handlers not firing should you need to add any LinkButtons or anything like that to your table cells
The question is where are you adding these rows in the table, I mean in which event of page?
As I feel that post back is clearing all the added rows.
Kindly tell the execution sequence and also try to put your code in page_init event for adding rows.
Might solve your problem.
Make table runat="server" in your aspx code
<table id="tbl" runat="server">
</table>
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TableRow tr = new TableRow();
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
// Add the control to the TableCell
tc.Controls.Add(txtBox);
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
// Add the TableRow to the Table
tbl.Rows.Add(tr);
}
}

asp.net ListView Sorting using DataBind

Sort listview using column headings in the LayoutTemplate
I am able to sort a basic list view using asp:SqlDataSource and setting the list view property DataSourceID by pointing it to the asp:SqlDataSource ID. I am having an issue when sorting when not using the asp:SqlDataSource and just DataBinding from the code behind.
SqlDataSource Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
<asp:SqlDataSource ID="ContactsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MainConnString %>"
SelectCommand="SELECT * FROM TableName">
</asp:SqlDataSource>
DataBind Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
protected void Page_Load(object sender, EventArgs e)
{
String SQL = "SELECT * FROM Customer";
SqlDataAdapter da= new SqlDataAdapter(SQL, ConnStr);
DataSet ds = new DataSet();
da.Fill(ds);
ContactsListView.DataSource = ds.Tables[0];
ContactsListView.DataBind();
}
Both code samples populate the list view, but the second example data binding does not work for sorting. With the first example, the sorting just works with the added asp:LinkButton in the LayoutTemplate adding the CommandName="sort" and setting the CommandArugment="ColumnName", but it does not work with the second example.
Can anyone please explain why and how to get the sorting working using the code behind DataBind method?
Thanks!
I solved my issue.
I added an event to handle the sorting. The event grabs the command name (Data column) and passes it and the sorting direction into a function which will make another call to the database sort the returned results and rebind to the List View.
I had to create a view state to hold the List View Sort Direction because for some reason, the onsorting event handler kept saying that the sort direction was ascending.
Front End
<asp:ListView ID="ContactsListView" OnSorting="ContactsListView_Sorting" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
Back End
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindContacts(string.Empty);
}
}
protected SortDirection ListViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void ContactsListView_Sorting(Object sender, ListViewSortEventArgs e)
{
BindContacts(e.SortExpression + " " + ListViewSortDirection.ToString());
// Check the sort direction to set the image URL accordingly.
string imgUrl;
if (ListViewSortDirection == SortDirection.Ascending)
ListViewSortDirection = SortDirection.Descending;
else
ListViewSortDirection = SortDirection.Ascending;
}
private void BindContacts(string sortExpression)
{
sortExpression = sortExpression.Replace("Ascending", "ASC");
sortExpression = sortExpression.Replace("Descending", "DESC");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM Customer", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
// Sort now
dTable.DefaultView.Sort = sortExpression;
// Bind data now
ContactsListView.DataSource = dTable;
ContactsListView.DataBind();
}
conn.Close();
}
}
I guess you could try to add a handler for ListView's Sorting event. There you are given the sorting column and the sort order in the event arguments. This could be easily usable to build a specific query and bind it to the list.
Because depending on the sort expression (which you defined in your markup) SqlDataSource will very likely do something like this (I'm not sure this is exactly what it does) for you behind the scenes:
Expression<Func<DataRow,object>> myExpression = row => row["SortExpressionYouDefinedForTheColumn"];
IEnumerable<DataRow> ex = ds.Tables[0].AsEnumerable().OrderBy(myExpression.Compile());
Or SqlDataSource may be using a DataView to sort the DataTable.
SqlDataSource can do this because by default it uses a DataSet to store the result set (or so says the documentation):
The data retrieval mode identifies how a SqlDataSource control retrieves data from the underlying database.
When the DataSourceMode property is set to the DataSet value, data is
loaded into a DataSet object and stored in memory on the server. This
enables scenarios where user interface controls, such as GridView,
offer sorting, filtering, and paging capabilities..
Since you chose to bind manually to a DataSet, you need to do the "magic" yourself; in other words, you handle the OnSort command, get the sort expression, get your data source again (however you do it, from Session or by calling the database again) and do your sort similarly to the lines shown above and rebind to your Gridview.

Populate ListView with data from server

I have a ListView on my checkout page with an ItemTemplate which build up a table of items ordered by customer. I want to add a total in the footer of the table, I have the following markup:
<asp:ListView ID="lvOrderSummary" runat="server">
<LayoutTemplate>
<table id="tblOrderSummary">
<tr>
<td><b>Title</b></td>
<td><b>Cost</b></td>
</tr>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
<tr>
<td><b>Total Cost:</b></td>
<td><%# GetTotalCost().ToString()%></td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("Title") %></td>
<td><%#Eval("Cost") %> </td>
</tr>
</ItemTemplate>
</asp:ListView>
I have a server side method called GetTotalCost that return the value I require. The problem I'm having is that this method is never called.
I have also tried and instead of using:
<td><%# GetTotalCost().ToString()%></td>
I've tried using
<td id="tdTotal" runat="server"></td>
---------------
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TableCell td = ((TableCell)this.FindControl("lvOrderSummary_tdTotal"));
}
}
Check this article for an example how to display a total in the ListView.
Basically you can add a label in the layout template:
<asp:ListView ID="lvOrderSummary" runat="server"
OnPreRender="lvOrderSummary_PreRender" ...>
<LayoutTemplate>
...
<td><asp:Label ID="lblTotalCost" runat="server" Text="Total"/></td>
..
</LayoutTemplate></asp:ListView>
And then you set the label's text in the PreRender event handler:
protected void lvOrderSummary_PreRender(object sender, EventArgs e)
{
Label lbl = lvOrderSummary.FindControl("lblTotalCost") as Label;
lbl.Text = GetTotalCost().ToString();
}
Try
Dim strcon As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=D:\webarticles\App_Data\mydatabase.mdf;Integrated Security=True;User Instance=True"
Dim con As New SqlConnection(strcon)
con.Open()
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim sqlstring As String = "SELECT * FROM tblstudent "
da = New SqlDataAdapter(sqlstring, con)
da.Fill(ds)
DetailsView1.DataSource = ds.Tables(0)
DetailsView1.DataBind()
Catch ex As Exception
MsgBox("There is some Error")
End Try
Another data handeling control is DetailsView control which gives you the ability to display, delete, edit, insert a single record at a time from its associated data source. The DetailsView control does not support sorting.By default, the DetailsView control displays each field of a record on its own line.

Resources