Problems with Radio button in the datalist - c#

Guys before asking this questions I did a lot of research on this topic but I am not able to detect the problem.I have radio button in the datalist and I am trying to get the selected radio button value.But it is showing me false for all radio button on submit button.My datalist is like this:
<asp:DataList ID="dlEmails" RepeatLayout="Flow" runat="server" >
<HeaderTemplate>
<table>
<tr>
<th>Select Email Address </th>
<th>Status</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:RadioButton ID="rbtnSelect" Text='<%#Eval("Emails") %>' onclick='fnrad(this);' GroupName="a" Checked='<%#Eval("Primary") %>' runat="server" /><br />
(<asp:Label ID="lablel" runat="server" Text='<%#Eval("Verified") %>'> </asp:Label>)
</td>
<td valign="middle">
<asp:Label ID="lblID" Style="display: none;" runat="server" Text='<%#Eval("Id") %>'> </asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Main") %>'> </asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
Javascript for allowing only single radio button selection at a time is like this:
<script>
function fnrad(rbtn) {
var radioList = document.getElementsByTagName("input");
for (var i = 0 ; i < radioList.length; i++) {
if (radioList[i].type == "radio") {
radioList[i].name = 'a';
radioList[i].checked = false;
}
}
rbtn.checked = true;
rbtn.setAttribute("Checked","checked");
}
</script>
And my code behind is like this:
public partial class Member_EmailList : System.Web.UI.Page
{
EmailsBAL _mbl = new EmailsBAL(SessionContext.SystemUser);
DataSet _ds = new DataSet();
URLMessage URLMessage = new URLMessage();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
_mbl.LoadByUser(_ds, 1);//SessionContext.SystemUser;
dlEmails.DataSource = _ds.Tables[_mbl.SqlEntityX];
dlEmails.DataBind();
}
protected void lnkConfirm_Click(object sender, EventArgs e)
{
RadioButton rb;
Label lbl;
int id = 0;
foreach (DataListItem di in dlEmails.Items)
{
rb = (RadioButton)di.FindControl("rbtnSelect");
if (rb.Checked == true)
{
lbl = (Label)di.FindControl("lblID");
id = WebHelper.Cast(lbl.Text, 0);
}
}
//Response.Redirect("~/Member/ConfirmEmail.aspx?" + URLMessage.Encrypt("SystemUser=" + SessionContext.SystemUser + "Id=" + id.ToString()));
}}

I tried your javascript function and experienced your problem
I would like to suggest to use Jquery on your javascript function. I refactored your jav fuction to this.
function fnrad(rbtn) {
$('input').removeAttr('checked');
$(rbtn).prop('checked', true);
}
This works perfectly on my end. Please let me know if you still encountering the issue.

Related

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

Checkboxlist inside a usercontrol going as null when control passed from an aspx page

Have landed into a scenario again. The summary is as follows:
I have a user-control which is basically a mix up of a textbox,imagebuttons,checkboxlist incorporated together to look like a single-select dropdown with checkboxes..works pretty fine. One of the images inside the usercontrol opens up an aspx page as a popup.have few functionalities there viz saving values to database and stuffs.
On the OK button click of the popup page, I should be able to save the values to the DB as well as populate the usercontrol(which acts as a dropdown) with the value which I have saved to the DB.
Here the problem arises, when trying to bind the checkboxlist(present in the usercontrol) to the values from the DB, I get the error that the checkboxlist object is null and has not been created.
I feel that on the OK button click, the usercontrol has to refresh and hence the checkboxlist will be active.
PFB the relevant codes:
Usercontrol.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SingleSelectCustomDropDown.ascx.cs" Inherits="MS.IT.Informa.UI.UserControls.SingleSelectCustomDropDown" %>
<asp:Panel ID="panel" runat="server">
<div id="FirstDiv">
<table>
<tr>
<td align="right">
<asp:TextBox ID="txtSelect" runat="server" ReadOnly="true"></asp:TextBox>
</td>
<td>
<asp:Image ID="imgShow" ImageUrl="../Images/DDGlyph.png" onmouseover="this.src='../Images/DDGlyphHOVER.png'" onmouseout="this.src='../Images/DDGlyph.png'" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="SecondDiv" style="display:none;">
<asp:CheckBoxList ID="chkBoxList" runat="server">
<asp:ListItem Value="0" Text="Standard" Selected="True"></asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="ThirdDiv" style="display:none;">
<asp:ImageButton ID="btnNew" runat="server" Height="20px" ImageUrl="~/Images/new.png" Width="20px" OnClientClick="ShowPopup();" />
<asp:ImageButton ID="btnEdit" runat="server" Height="20px" ImageUrl="~/Images/edit.png" Width="20px" />
<asp:ImageButton ID="btnDefault" runat="server" Height="20px" ImageUrl="~/Images/default.png" Width="20px" />
<asp:ImageButton ID="btnDelete" runat="server" Height="20px" ImageUrl="~/Images/delete.png" Width="20px" />
</div>
</td>
</tr>
</table>
</div>
</asp:Panel>
<script type="text/javascript">
//Displays the divs containing checkboxlist and images
function ShowList() {
document.getElementById("SecondDiv").style.display = "block";
document.getElementById("ThirdDiv").style.display = "block";
}
//Hides the divs containing checkboxlist and images
function HideList() {
document.getElementById("SecondDiv").style.display = "none";
document.getElementById("ThirdDiv").style.display = "none";
}
//Displays the selected item from the checkboxlist into the textbox placed in the Custom Control
function DisplaySelectedItem(sender, txtBoxID) {
var x = document.getElementById(sender.id);
var chkBoxPrefix = sender.id + "_";
var selectedText;
for (i = 0; i < x.rows.length; i++) {
if(document.getElementById(chkBoxPrefix+i).checked)
{
selectedText = document.getElementById(chkBoxPrefix+i).parentNode.innerText;
}
}
document.getElementById(txtBoxID.id).value = selectedText;
}
//Ensures that only one item is selected from the checkboxlist
function SelectOnlyOneCheckBox(e) {
if (!e) e = window.event;
var sender = e.target || e.srcElement;
if (sender.nodeName != 'INPUT') {
return;
}
var checker = sender;
var chkBox = document.getElementById('<%= chkBoxList.ClientID %>');
var chks = chkBox.getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
if (chks[i] != checker)
chks[i].checked = false;
}
}
function ShowPopup() {
window.open("ViewColumnOptions.aspx", "ViewColumnOptions", "height=300,width=600,left=300,top=150");
}
</script>
The codebehind for the usercontrol as below:
public partial class SingleSelectCustomDropDown : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
chkBoxList.Attributes.Add("onclick", "SelectOnlyOneCheckBox(event);DisplaySelectedItem(this," + txtSelect.ClientID + ");HideList();");
txtSelect.Attributes.Add("onclick", "ShowList();");
imgShow.Attributes.Add("onclick", "ShowList();");
}
}
public void PopulateOtherViews()
{
SaveReportViewFilter<ReportFilterBase> newObj = new SaveReportViewFilter<ReportFilterBase>();
ViewColumnOptions vwobj = new ViewColumnOptions();
newObj.UserName = vwobj.Page.User.Identity.Name;
SaveReportView<ReportFilterBase> obj2 = new SaveReportView<ReportFilterBase>();
DataTable dt = obj2.GetSaveReportViewFromDataBase(newObj);
chkBoxList.DataSource = dt;//chkBoxList becomes null here..we have ample data in the datatable though
chkBoxList.DataTextField = dt.Columns[0].ToString();
chkBoxList.DataValueField = dt.Columns[0].ToString();
chkBoxList.DataBind();
}
}
The function PopulateOtherViews is called on the button click of the aspx page.
Below is the code:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(),"close","CloseWindow();",true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}
Any help, suggestions, pointers will be greatly appreciated.
Regards
Anurag
In btnOK_Click you are creating a new instance of the user control and not attaching it to the page. My suggestion is:
1.Register the user control and add it to the page.
<%# Register Src="~/UserControl/SingleSelectCustomDropDown.ascx" TagPrefix="uc1" TagName="SingleSelectCustomDropDown" %>
and ...
<uc1:SingleSelectCustomDropDown runat="server" id="obj22" />
2.Now modify in code behind:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
//Do not create the control again
//SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "CloseWindow();", true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}

How I use the ItemCommand Event for my ListView in my ASP.NET Application

I have a ASP.NET Application with a ListView. In every Row in my ListView I have a LinkButton that open a new webform "Benutzer.aspx". my Problem is that I don't get the Index of this Row. I use the ItemCommand Event but it not work :(
Here my Code:
ASPX:
...
<ItemTemplate>
<tr runat="server">
<td align="left" ><asp:Label ID="Label1" Text='<%# Eval("Benutzer") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label2" Text='<%# Eval("eMail") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label3" Text='<%# Eval("Vorname") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label4" Text='<%# Eval("Nachname") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label5" Text='<%# Eval("Telefon") %>' runat="server" /></td>
<td align="left"><asp:LinkButton runat="server" Text="Anzeigen" CommandName="Anzeigen" OnCommand="ListView1_ItemCommand" CommandArgument="myArguments"></asp:LinkButton></td>
</tr>
</ItemTemplate>
...
cs file:
...
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Anzeigen")
{
Label lbText = (Label)e.Item.FindControl("Label2");
string email = lbText.Text;
Session["email"] = email;
Response.Redirect("Benutzer.aspx");
}
}
...
What is the matter :(
tarasov
Try this:
First you need to have the index of the button. So in the html code add this in the CommandArgument of the button to get the index:
CommandArgument='<%# Container.DataItemIndex %>'
Then in the codebehind:
if (e.CommandName == "Anzeigen")
{
Label lbText = ListView1.Item[e.CommandArgument].FindControl("Label2");
string email = lbText.Text;
Session["email"] = email;
Response.Redirect("Benutzer.aspx");
}
Hope I Helped
You cannot find the control because it is contained in the child control collection of another server control:
<tr runat="server">
You need to try to find the control recursively:
Take a look
Better way to find control in ASP.NET
Or you can use this extension method:
public static class ControlExtensions
{
public static Control FindControlRecursively(this Control control, string targetControlID)
{
if (control == null)
{
return null;
}
var ctrl = control.FindControl(targetControlID);
if (ctrl == null)
{
foreach (Control child in control.Controls)
{
ctrl = FindControlRecursively(child, targetControlID);
if (ctrl != null)
{
break;
}
}
}
return ctrl;
}
}
Usage:
var ctrl = e.Item.FindControlRecursively("your control ID");
The code you have furnished is simply fine... "just remove the 'CommandArgument' from your listview property , bcoz..its already have the dataindex you are looking for. By specifying a command argument you are overriding the default one.
So just remove the command argument and your code will work fine... :)
I am a VB programmer Check this method may b it gives you some idea
after binding the list with datasource, In the itemCommand do this
Dim <sometext> As Label = TryCast(e.Item.FindControl("Anzeigen"), Label)
If e.CommandName = "Anzeigen" Then
'do what ever you like
'also you can use <sometext> if you want to extract data from list
'simply use <sometext>.<whatproperty>, you can also store it in sessions like the email you are using.
Session("email") = email
Response.Redirect("Benutzer.aspx");
End If
let me know if it helps you solve your problem.
This is the HTML, then build the OnItemCommand.
<asp:ListView ID="lvFiles" runat="server" DataKeyNames="FileName" OnItemCommand="lvFiles_ItemCommand">
<ItemTemplate>
<tr runat="server">
<td style="width:80px">
<asp:LinkButton runat="server"
ID="SelectEmployeeButton"
Text="Download File"
CommandName='<%#Eval("FileName")%>'
CommandArgument='<%#Eval("FileName")%>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Here is the code behind...
protected void lvFiles_ItemCommand(object sender, ListViewCommandEventArgs e)
{
string v = e.CommandArgument.ToString();
}

Bind 5 items in each row of repeater

I have a set of items coming from the database. Their number may vary. I have bound them in a repeater. Now my following example will explain what I want:
I have 11 items coming from database, I want them to be grouped in terms of 5 items per row.
1st row: 5 items.
2nd row: 5 items.
3rd row: 1 item.
Currently, I am just binding them in a repeater. How do I do this?
Yes. It is possible:
<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
<asp:Literal runat="server" Text='<%# Eval("Value") %>'></asp:Literal>
<div style="clear: both" runat="server" Visible="<%# (Container.ItemIndex+1) % 5 == 0 %>"></div>
</ItemTemplate>
</asp:Repeater>
It produces following results for the sequence of numbers:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
if you can use ListView, then you can use GroupItemCount . some thing like this MSDN Example
<asp:ListView ID="ContactsListView"
DataSourceID="yourDatasource"
GroupItemCount="5"
runat="server">
<LayoutTemplate>
<table id="tblContacts" runat="server" cellspacing="0" cellpadding="2">
<tr runat="server" id="groupPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<div> your Items here </div>
</ItemTemplate>
<GroupTemplate>
<tr runat="server" id="ContactsRow" style="background-color: #FFFFFF">
<td runat="server" id="itemPlaceholder" />
</tr>
</GroupTemplate>
<ItemSeparatorTemplate>
<td runat="server" style="border-right: 1px solid #00C0C0"> </td>
</ItemSeparatorTemplate>
</asp:ListView>
If you want to stick with a Repeater, I can think of two approaches.
Firstly, you could stick with a flat list of items and make the repeater insert a "new line" after each 5th item. You should be able to do this in the <ItemTemplate> with a block like
<% if ((Container.DataItemIndex % 5) == 4) { %>
</div>
<div>
<% } %>
which honestly isn't very nice.
Alternatively, you could use MoreLINQ's Batch method to batch your items up into IEnumerables of 5, and then use two nested repeaters to render them. Set the outer repeater to wrap the inner repeater in <div> tags, and set the inner repeater's DataSource='<%# Container.DataItem %>'. This should result in much cleaner markup.
You can try below, I mistakenly said ListView, actually I meant DataList
<asp:DataList ID="DataList1" runat="server" RepeatColumns="5"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<ItemTemplate >
<%--Your Item Data goes here--%>
</ItemTemplate>
</asp:DataList>
You may use nested Data controls (i.e Repeater) and also handle the OnItemDataBound event to bind the inner Repeater.
Sample Data Source component:
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<List<Item>> getItems()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
/* Split the list as per specified size */
int size = 2;
var lists = Enumerable.Range(0, (list.Count + size - 1) / size)
.Select(index => list.GetRange(index * size,
Math.Min(size, list.Count - index * size)))
.ToList();
return lists;
}
}
Markup (.aspx)
<asp:Repeater ID="outerRepeater"
runat="server" onitemdatabound="outerRepeater_ItemDataBound"
>
<ItemTemplate>
<p>
Row
</p>
<asp:Repeater ID="innerRepeater"
runat="server">
<ItemTemplate>
<asp:Literal ID="literal1" runat="server" Text='<%# Eval("ID") %>' />
<asp:Literal ID="literal2" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
outerRepeater.DataSource = Item.getItems();
outerRepeater.DataBind();
}
}
protected void outerRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Repeater repeater = e.Item.FindControl("innerRepeater") as Repeater;
repeater.DataSource = Item.getItems()[e.Item.ItemIndex];
repeater.DataBind();
}
<asp:Repeater ID="Repeater1" runat="server"
OnItemDataBound="Repeater1_databinding">
<HeaderTemplate>
<table id="masterDataTable" class="reportTable list issues" width="100%">
<thead>
<tr>
<asp:Literal ID="literalHeader" runat="server"></asp:Literal>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<asp:Literal ID="literals" runat="server"></asp:Literal>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody> </table>
</FooterTemplate>
</asp:Repeater>
<input id="hdnColumnName" runat="server" clientidmode="Static" type="hidden" />
<input id="hdnColumnOrder" runat="server" clientidmode="Static" type="hidden" />
// javascript Function
<script type="text/javascript">
$(document).ready(function () {
$('#ddlReport').removeClass('required');
$('.sort').click(function () {
$('#hdnColumnName').val($(this).text());
$('#hdnColumnOrder').val($(this).attr('class'));
$(this).toggleClass("desc asc");
$("#lnkSort").click();
});
});
</script>
// Bind repeater
DataTable dt = objReport.GetCustomRecord();
fn = new List<string>();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName != "Maxcount" )
{
fn.Add(dt.Columns[i].ColumnName);
}
}
Repeater1.DataSource = dt;
Repeater1.DataBind();
protected void Repeater1_databinding(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
if (e.Item.FindControl("literalHeader") != null)
{
StringBuilder sb = new StringBuilder();
Literal li = e.Item.FindControl("literalHeader") as Literal;
fieldName().ForEach(delegate(string fn)
{
if (hdnColumnName.Value != fn.ToString())
{
sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort desc\" onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\" >"
+ fn.ToString() + "</a></th>");
}
else
{
if (hdnColumnOrder.Value == "sort asc")
sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort desc\" onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\" >"
+ fn.ToString() + "</a></th>");
else
sb.Append("<th width=\"10%\"> <a id=\"btnCustomerName\" class=\"sort asc\" onclick=\"btnSorts_onclick()\" style=\"cursor:pointer;text-decoration: none !important;\">"
+ fn.ToString() + "</a></th>");
}
});
li.Text = sb.ToString();
}
}
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.Item.FindControl("literals") != null)
{
DataRowView drv = (DataRowView)e.Item.DataItem;
Literal li = e.Item.FindControl("literals") as Literal;
StringBuilder sb = new StringBuilder();
fieldName().ForEach(delegate(string fn)
{
sb.Append("<td>" + drv[fn.ToString()] + "</td>");
});
li.Text = sb.ToString();
}
}
}

Want Checked Item From Listview

I am working with listview in C# webapplication. My Problem is I want checked Items from the listview . I have try with find selecteditem and all. I dont know how to get checked items from checkbox inside listview.My code is as follows:-
aspx
<asp:ListView ID="PackagesListView" runat="server" DataSourceID="PackagesDataSource" ItemPlaceholderID="itemPlaceholder"
GroupItemCount="4" GroupPlaceholderID="groupPlaceholder" OnItemDataBound="PackagesListView_ItemDataBound">
<LayoutTemplate>
<table style="margin-left:0px; width:570; table-layout:fixed; overflow:hidden;">
<tr ID="groupPlaceholder" runat="server" >
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr class="productsTableRow">
<td ID="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td style="width:140px;">
<div style="text-align:center; line-height:1.5;"><asp:Label ID="PackageLabel" runat="server" Text='<%#Eval("Name")%>' /></div>
<div style="text-align:center;"><asp:CheckBox ID="PackageCheckBox" runat="server" OnCheckedChanged="OnPackageSelected" AutoPostBack="true" PackageID='<%#Eval("PackageID")%>' /></div>
</td>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="ButtonSaveQuotation" runat="server" Text="Save Quotation"
CssClass="button" Visible="false" onclick="ButtonSaveQuotation_Click1" />
aspx.cs
protected void ButtonSaveQuotation_Click1(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
}
so here in sb I want to append text of all the label whose checkboxes are checked.Thank You
You will have to find the checkbox since it's inside the template field
Example:
if (PackagesListView.Items.Count > 0)
{
for (int i = 0; i < PackagesListView.Items.Count; i++)
{
CheckBox PackageCheckBox= (CheckBox)PackagesListView.Items[i].FindControl("PackageCheckBox");
if (PackageCheckBox!= null)
{
if (PackageCheckBox.Checked.Equals(true))
{
//do your stuff here
}
}
}
}
foreach (var item in PackagesListView.Items.Where(i => ((CheckBox)i.FindControl("PackageCheckBox")).Checked))
{
var label =(Label) item.FindControl("PackageLabel");
label.Text += " Appended text";
}
Perhaps this will help you? This should go after page load. Also make sure you are not rebinding your listview.
var texts = PackagesListView.Items.Cast<Control>()
.Where(c => ((CheckBox)c.FindControl("PackageCheckBox")).Checked)
.Select(c => ((Label)c.FindControl("PackageLabel")).Text);
var sb = new StringBuilder();
foreach ( var text in texts)
sb.AppendLine(text);

Categories