Working with Datalist in asp.net? - asp.net

good morning to all.
i place a datalist in my project in that i place a link button when i click on that link button a panel will open in that row with a textbox and a button. it is working fine but my problem is if i click on one link button of a row panel will open, when i click on second row link button the sencond row panel is opening but first row panel is not closing. I think you get my point owhter wise i will explain again this is my code check out
<form id="form1" runat="server">
<div>
<asp:DataList ID="Mydatalist" runat ="Server"
OnItemCommand="Mydatalist_ItemCommand" >
<ItemTemplate >
<table >
<tr>
<td>
<asp:Label ID="lblcouname" runat ="server"
Text ='<%# Eval("country_name") %>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="lnkrepl" Text="reply"
CommandName ="reply" runat ="server"
CommandArgument ='<%# Eval("country_id") %>'>
</asp:LinkButton>
</td>
</tr>
</table>
<div>
<asp:Panel ID="mypane" runat ="Server" Visible ="false" >
<asp:TextBox ID="txtpane" runat ="Server" ></asp:TextBox><br />
<asp:Button ID="btnInsert" runat="Server" Text ="Insert" />
</asp:Panel>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
Code behind:
public partial class Datlist : System.Web.UI.Page
{
SqlConnection con; SqlDataAdapter da; DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(
#"server=msmsm;database=pop;user id=sa;password=abc");
con.Open();
if (!IsPostBack)
{
getCountry();
}
}
public void getCountry()
{
string sqr="select * from country";
da=new SqlDataAdapter (sqr,con);
ds = new DataSet();
da.Fill(ds,"country");
Mydatalist.DataSource = ds.Tables[0];
Mydatalist.DataBind();
}
protected void Mydatalist_ItemCommand(object source, DataListCommandEventArgs e)
{
Panel pn = (Panel)e.Item.FindControl("mypane");
pn.Visible = false;
if (e.CommandName == "reply")
{
pn.Visible = true;
}
}
}

You have to programmably hide it. THe DataList should have an items property, and as such you can loop through all items, find the panel control using FIndControl, and set its visibility to false.
EDIT: So you need to do:
private void HideItems()
{
foreach (var item in this.dl.Items)
{
var panel = item.FindControl("mypane") as Panel;
if (panel != null)
panel.Visible = false;
}
}
In ItemCommand, call this method to hide all the existing control's panels.

Related

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.

UpdatePanel sometimes refreshing entire page

Even though I am using an update panel, sometimes my entire page is refreshed, and I can't figure out why.
(Edited to take into account Jason P's answer.)
Masterpage code:
<form runat="server" id="form1">
<asp:ScriptManager ID="ScriptManager1" runat="server" enablePartialRendering="true" />
<h1>Title</h1>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" childrenAsTriggers="true">
<ContentTemplate>
<ul class="letterLinks">
<asp:Repeater runat="server" ID="Letter_Repeater">
<ItemTemplate>
<li id='<%#Eval("Letter")%>'>
<asp:LinkButton runat="server" ID="UpdateLink" Text="My Text"
CommandName="BookLetter" CommandArgument='<%#Eval("Letter")%>' OnCommand="LoadBookTitles"/>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<ul class="BookList">
<asp:Repeater runat="server" ID="Title_Repeater">
<ItemTemplate>
<li><a href='<%#Eval("URL")%>'><%#Eval("Title")%></a></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Code Behind:
public partial class MyBooks : System.Web.UI.MasterPage
{
private GetAllBookInfo setMyInfo = new GetAllBookInfo();
private DataTable allTitleInfo = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
List<string> lettersWithBooks = new List<string>();
DataTable letterLinks = new DataTable();
// Get all letters that have Books
lettersWithBooks = setMyInfo.LettersWithBooks();
// get properties for ABC links
letterLinks = GetLetterLinkProperties(lettersWithBooks);
// Bind abc link data to the ABC repeater
Letter_Repeater.DataSource = letterLinks;
Letter_Repeater.DataBind();
allTitleInfo = setMyInfo.GetBookTitles(lettersWithBooks[0]);
// Bind title info data to title repeater
Title_Repeater.DataSource = allTitleInfo;
Title_Repeater.DataBind();
}
private DataTable GetLetterLinkProperties(List<string> letters)
{
DataTable letterLinks = new DataTable();
letterLinks.Columns.Add("Letter", typeof(string));
letterLinks.Columns.Add("Class", typeof(string));
letterLinks.Columns.Add("Enabled", typeof(bool));
for (char c = 'A'; c <= 'Z'; c++)
{
if (letters.Any(letter => letter == c.ToString()))
{
letterLinks.Rows.Add(c, "hasGuides", true);
}
else
{
letterLinks.Rows.Add(c, "noGuides", false);
}
}
return letterLinks;
protected void LoadBookTitles(object sender, EventArgs e)
{
LinkButton letterLink = (LinkButton)sender;
allTitleInfo = setMyInfo.GetBookTitles(letterLink.CommandArgument as String);
// Bind title info data to title repeater
Title_Repeater.DataSource = allTitleInfo;
Title_Repeater.DataBind();
}
}
Not sure if this is the entire problem, but the <Triggers> element should be on the same level as the <ContentTemplate> element, not a child:
<asp:UpdatePanel>
<Triggers>
...
<Triggers>
<ContentTemplate>
...
<ContentTemplate>
</asp:UpdatePanel>
Also, I believe in this case, the Repeater should be the trigger, not the LinkButton. Try removing the OnCommand event from the LinkButton and adding it to the Repeater, and changing the UpdatePanel's Trigger.

Repeater inside repeater not binding properly

I have a repeater inside another. Like so :
<asp:Repeater ID="CategoryRepeater" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="groupbox">
<fieldset>
<legend><%# Container.DataItem %></legend>
<table>
<asp:Repeater ID="ItemRepeater" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox id="chkItem" runat="server" Text='<%# Eval("Text")%>' />
<asp:Button ID="btnXRefs" Text="x-refs" runat="server" CssClass="xRefButton" OnClick="btnSelectXRefs_Click" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</fieldset>
</div>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (var db = new DbContext())
{
CategoryRepeater.DataSource = db.Categories.OrderBy(x => x.Heading).Select(x => x.Heading).Distinct();
CategoryRepeater.DataBind();
}
}
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item)
{
Repeater childRepeater = (Repeater)args.Item.FindControl("ItemRepeater");
var item = args.Item as RepeaterItem;
using (var db = new DbContext())
{
childRepeater.DataSource = db.Categories.Where(x => x.Heading == item.DataItem).OrderBy(x => x.Text);
childRepeater.DataBind();
}
}
}
My goal is to first make many groupboxes using the top level, then bind items into each one. So I end up with many small stacked lists of checkboxes.
Problem is, all the top level boxes appear, yet only the first one contains checkbox items, ie. only the first one is bound internally, and the ItemBound method is only called once for the first one.
Any ideas why?
This line
if (args.Item.ItemType == ListItemType.Item)
Should be like this
if(args.Item.ItemType = ListItemType.Item ||
args.Item.ItemType == ListItemType.AlternatingItem)

select index of listView is not working in ASP.NET

I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
Now I want to retrieve all this data in my <div> tag. so i tried using asp:ListView,
here is my code snippet,
it works properly, but now i want to navigate to new page when user select any row of listView, but i am unable to select any row..
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
</div>
</ItemTemplate>
Thanks In Advance !!
Any help will be appreciated.
EDIT:(SearchBox.aspx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class SearchBox : System.Web.UI.Page
{
string connString;
DataTable result = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{ }
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("NextPage.aspx?id=" + lablId.Text, false);
}
}
(SearchBox.aspx)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchBox.aspx.cs" Inherits="SearchBox" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="179px"
OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Go"
Width="62px" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="false" runat="server" Text='<%#Eval("Scrip") %>'/>
</div>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:krunal_DBConnectionString2 %>"
SelectCommand="SELECT * FROM [SearchBoxData]"></asp:SqlDataSource>
</form>
</body>
</html>
You have to add a SELECT button in the ItemTemplate, see the complete working code.
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Scrip")%>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:ListView>
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("CONTROL_ID");
}
Thanks
Deepu
Probably you will have to add the event for Selected index change:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging">
In code behind you can get the selected row item like below.
Also you can place a label or hidden field so that you can get some data from those control and pass it in to the next page.. (might be id or something).
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="flase" runat="server" Text='<%#Eval("Id") %>' />
</div>
</ItemTemplate>
</asp:ListView>
void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("page.aspx?id="+lablId.Text,false);
}
}
Thanks
Deepu
Here you go,
Also remove the OnClick="callMethod" from the button. Since you have SelectedIndex method no need to have the onClick method.
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Button btn = (Button)item.FindControl("btn1");
if(btn != null)
{
var buttonText = btn.Text;
}
}
Hope this helps
Thanks
Deepu

Asp.Net ListView's Items property is always empty

Good day
I have a user control that contains a ListView which is being used to display tabs.
I am databinding the ListView and on the OnItemDataBound event adding the tab elements.
However the Items property never contains anything and is always empty (on PostBack and on ItemDataBound).
Markup:
<asp:ListView ID="SaleTabsListView" runat="server" OnItemDataBound="SaleTabsListView_OnItemDataBound" ItemPlaceholderID="SaleTabsPlaceHolder" EnableViewState="true">
<LayoutTemplate>
<div class="tabs">
<asp:PlaceHolder runat="server" ID="SaleTabsPlaceHolder" />
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:PlaceHolder runat="server" ID="ItemPlaceHolder" />
</ItemTemplate>
</asp:ListView>
Code behind:
protected void SaleTabsListView_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
var saleTab = ((ListViewDataItem)e.Item).DataItem as SalesTab;
if (saleTab != null)
{
var placeHolder = e.Item.FindControl("ItemPlaceHolder") as PlaceHolder;
var htmlAnchor = new HtmlAnchor();
htmlAnchor.Attributes.Add("id", saleTab.Id);
htmlAnchor.Attributes.Add("class", saleTab.IsCurrent ? currentTabClass : string.Empty);
var emptyLabel = new Label();
var label = new Label {Text = saleTab.Title};
label.Attributes.Add("id", saleTab.Id + "Label");
label.Attributes.Add("class", saleTab.IsComplete ? completeClass : incompleteClass);
emptyLabel.Controls.Add(label);
htmlAnchor.Controls.Add(emptyLabel);
placeHolder.Controls.Add(htmlAnchor);
}
}
}
So my question is: is the binding I'm doing somehow screwing with the Items property?
Thanks

Resources