I have a ListView with a checkbox field inside that gets the id set dynamically.
I also have a button that when pressed needs to check if any of the checboxes have been checked but I'm not sure how to get this done.
Any idea on how I can get this done?
Thanks
This is my code:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id"
DataSourceID="EntityDataSource1" EnableModelValidation="True">
<ItemTemplate>
<tr>
<td class="firstcol">
<input id='Checkbox<%# Eval("Id") %>' type="checkbox" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="50" scope="col" class="firstcol">
</th>
</tr>
<tr ID="itemPlaceholder" runat="server"></tr>
</table>
<asp:Button ID="btnDownload" runat="server" Text="Download" Height="26px"
onclick="btnDownload_Click" />
</LayoutTemplate>
</asp:ListView>
protected void btnDownload_Click(object sender, EventArgs e)
{
???????
}
disclaimer: I'm more of a back-end/wpf developer. There are likely more elegant solutions, but this seems to work.
Change your checkbox id so it is not unique (sorry, this will break w3c validation) and set it to runat server and set the value of the CheckBox to your data source's Id:
<ItemTemplate>
<tr>
<td class="firstcol">
<label runat="server"><%# Eval( "Id" ) %></label>
<input id="MyCheckBox" value='<%# Eval("Id") %>'
type="checkbox" runat="server" />
</td>
</tr>
</ItemTemplate>
You can then iterate through the ListView's items collection and find the CheckBoxes:
protected void btnDownload_Click( object sender, EventArgs e )
{
foreach( ListViewDataItem item in ListView1.Items )
{
var chk = item.FindControl( "MyCheckBox" ) as System.Web.UI.HtmlControls.HtmlInputCheckBox;
if( chk != null && chk.Checked )
{
string value = chk.Value;
}
}
}
If you wanted a bit of Linq:
protected void btnDownload_Click( object sender, EventArgs e )
{
var checkedCheckBoxes = ListView1.Items.Select( x => x.FindControl( "MyCheckBox" ) as HtmlInputCheckBox )
.Where( x => x != null && x.Checked );
// do stuff with checkedCheckBoxes
}
Related
I got some problem and let me spend some time on testing.
I have a ListView , and a checkbox inside this, and a button outside.
When I click button , will show the rows Tr ID that rows checkbox checked.
but it always show ctrl2 instead of ID.
This is my code:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<table cellspacing="0" border="0">
<tr>
<th scope="col" width="125">Man
</th>
<th scope="col" width="50">Type
</th>
<th scope="col" width="400">Reason
</th>
<th scope="col" width="125">date
</th>
<th scope="col" width="100">cheack
</th>
<th scope="col" width="125">remark
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr id="<%#Eval("ID").ToString()%>" runat="server">
<td scope="col" >
<%#Eval("UserID").ToString()%>
</td>
<td scope="col">
<%#Eval("Purpose").ToString() %>
</td>
<td scope="col">
<%#Eval("Reason").ToString() %>
</td>
<td scope="col">
<%#dateSession(Convert.ToDateTime( Eval("startTime"))) %>
</td>
<td scope="col">
<asp:CheckBox ID="CheckBox1" runat="server" Checked="True" />
</td>
<td scope="col">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
This is my code behind
protected void Btn_save_Click(object sender, EventArgs e)
{
foreach (ListViewItem row in this.ListView1.Items)
{
CheckBox stylistcheck = (CheckBox)row.FindControl("CheckBox1");
if (stylistcheck.Checked == true)
{
Response.Write(row.ID);
// Always get wrong ID , like 'ctrl3' not real rows Tr ID
}
}
}
Doing this <tr id="<%#Eval("ID").ToString()%>" runat="server"> will throw an error, AFAIR. If your goal is to get the ID for each row that represents your data then you can just add a literal control, hide it, and get it's value in code-behind. Something like:
<tr runat="server">
<td scope="col" >
<%# Eval("UserID").ToString()%>
<asp:Literal ID="idLiteral" runat="server" Text='<%# Eval("ID").ToString()%>' Visible="false" ></asp:Literal>
</td>
...rest of your code goes here...
</tr>
In code-behind, inside your if (stylistcheck.Checked == true) do a Response.Write(((Literal)row.FindControl("idLiteral")).Text); like so:
if (stylistcheck.Checked == true)
{
Response.Write(((Literal)row.FindControl("idLiteral")).Text);
}
CheckBox1.Checked = true;
It may help you.
OR
CheckBox chkDelete = (CheckBox)item.FindControl("CheckBox1");
if(chkDelete.Checked)
{
string yourID = item.DataItem["id"].ToString();
itemsToDelete.Add(yourID);
}
OR
if (CheckBox1.Checked==true)
{
}
This may also work for you.
yourListView.DataSource = GetCourses();
yourListView.DataBind();
var checkBox = yourListView.Controls.Cast<Control>).First().FindControl("yourID")
or
if (item.ItemType == ListViewItemType.DataItem){
CheckBox final = (CheckBox)item.FindControl("yourID");
if (final.Checked) {
}
Just wondering are you sure you can run this code ?
<tr id="<%#Eval("ID").ToString()%>" runat="server">
I tried your code and run it will encounter error on this line...
Because with " you will get error server tag is not well formed.
If i use this ' the error will be :
The ID property of a control can only be set using the ID attribute in the tag and a simple value.
I write the code which will retrieve ID might help you...
.aspx
<asp:ListView ID="ListView1" runat="server" >
<LayoutTemplate>
<table id="tbllol" runat="server" cellspacing="0" border="0">
<tr>
<th scope="col" width="100">cheack
</th>
<th scope="col" width="125">remark
</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td scope="col">
<asp:CheckBox ID="chkBox" runat="server" Checked="true" />
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' Visible="false"></asp:Label>
</td>
<td scope="col">
<asp:TextBox ID="txtRemarks" runat="server"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="btn_Click" />
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("ID");
// Loop & Add ID
for (int i = 0; i < 10; i++) dt.Rows.Add("myIDIi" + i);
ListView1.DataSource = dt;
ListView1.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e)
{
// Variable
string value = string.Empty;
// Loop
foreach (ListViewItem row in ListView1.Items)
{
// Find Control
CheckBox chkbox = row.FindControl("chkBox") as CheckBox;
Label lblID = row.FindControl("lblID") as Label;
// Check & Check Then Set to Value
if (chkbox != null && chkbox.Checked)
if (lblID != null) value += lblID.Text.Trim() + "<br />";
}
Response.Write(value);
}
I am using the code below to bind a Repeater:
<asp:Repeater ID="rptList" runat="server" OnItemCommand="rptList_ItemCommand">
<ItemTemplate>
<tr class="odd gradeX" id="trid" runat="server">
<td data-title="Code">
<asp:CheckBox ID="chkid" runat="server" AutoPostBack="false" />
<asp:HiddenField ID="hiddenid" runat="server" Value='<%#Eval("Visa_Type_Id") %>'/>
</td>
<td class="hidden-480"><%#Container.ItemIndex+1 %></td>
<td class="hidden-480">
<asp:LinkButton ID="lnk1" runat="server" CommandName="Edit" CommandArgument='<%#Eval("Visa_Type_Id") %>'><%#Eval("Visa_Type_Name") %> </asp:LinkButton>
</td>
<td class="hidden-480"><%#Eval("Visa_Description") %></td>
<td class=" " style="width: 100px;"><span class="label label-success">Active</span> <span class="label label-success">Publish</span></td>
</tr>
</ItemTemplate>
</asp:Repeater>
The code below is to check all the checkboxes:
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i <= rptList.Items.Count - 1; i++)
{
CheckBox chk = (CheckBox)rptList.Items[i].FindControl("chkid");
if (chk.Checked == true)
{
chk.Checked = false;
}
else
{
chk.Checked = true;
}
}
}
now by above code all the checkboxes in the Repeater are checked but I just want to check the ones which are displayed in paging. At the moment, if I am on page 1, using the above code, the boxes on page 2 are also checked.
Please help me.
you can use jQuery instead of server side code:
jsfiddle
$("#checkAll").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
I have some troubles with the textbox or my brain. I can't understand what's the reason of unedittable textbox. I mean, i have listview with 3 columns:"Name","Code","Binding".
By clicking on the "Name", the first and the second column become editable. After my edit, i push button "Save"...and nothing is happened. Can't understand such a simple thing. Why it's not working?
Sorry for mistakes, i'm here for the 1st time
<asp:Content ID="ContentMain" ContentPlaceHolderID="centerContent" runat="server">
<asp:Panel ID="i_ListContainer" runat="server" HorizontalAlign="Center">
<asp:ListView ID="CpzListView" runat="server" DataKeyNames="id" InsertItemPosition="FirstItem"
OnItemCreated="i_UserLV_ItemCreated" OnItemInserted="i_UserLV_ItemInserted" OnItemEditing="i_UserLV_ItemEditing"
OnItemInserting="i_UserLV_ItemInserting" OnItemUpdated="i_UserLV_ItemUpdated"
OnItemUpdating="i_UserLV_ItemUpdating">
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" class="mGrid">
<th style="width: 150px">
Name
</th>
<th style="width: 150px">
Code
</th>
<th style="width: 50px">
Binding
</th>
</thead>
<tbody>
<asp:PlaceHolder runat="server" ID="itemPlaceholder" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="i_viewEditLB" runat="server" CommandName="Edit" Text='<%#Bind("cpzname") %>' />
</td>
<td>
<asp:Label ID="i_viewUserFioLabel" runat="server" Text='<%#Bind("code") %>' />
</td>
<td style="text-align: center; width: 80px">
<a href='<%# GetUrl(Eval("cpzname"), Eval("code"))%>'>Bindindg</a>
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="tbCpzName" runat="server" Text='<%# Bind("cpzname") %>'></asp:TextBox>
</td>
<td>
<asp:TextBox ID="tbCpzCode" runat="server" Text='<%# Bind("code") %>'></asp:TextBox>
</td>
<td>
<asp:LinkButton ID="lbSave" runat="server" CommandName="Update" Text="Save" />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
</asp:Panel>
</asp:Content>
Here is the c# code, hope you'll help me.
namespace WebApplication2.MemberPages
{
protected void Page_Load(object sender, EventArgs e)
{
UpdateBinding();
}
private void UpdateBinding()
{
DataTable dt = AOneConnectDB.ExecuteQuery("select id, cpzname, code from cpz");
if (dt == null) return;
CpzListView.DataSource = dt;
CpzListView.DataBind();
}
protected void i_UserLV_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
CpzListView.EditIndex = -1;
UpdateBinding();
}
private string GetValue(users key)
{
return CpzListView.Items.Count > 0 ? CpzListView.SelectedDataKey[key.ToString()].ToString() : string.Empty;
}
protected void i_UserLV_ItemEditing(object sender, ListViewEditEventArgs e)
{
CpzListView.EditIndex = e.NewEditIndex;
CpzListView.SelectedIndex = e.NewEditIndex;
UpdateBinding();
}
protected void i_UserLV_ItemInserted(object sender, ListViewInsertedEventArgs e)
{
// must empty
}
private string ControlValue(string controlName, ListViewItem item)
{
object c = item.FindControl(controlName);
if (c is TextBox) return (c as TextBox).Text;
if (c is CheckBox) return (c as CheckBox).Checked ? ADataBase.TRUE : ADataBase.FALSE;
if (c is DropDownList) return (c as DropDownList).SelectedValue;
return null;
}
protected void i_UserLV_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
// must empty
}
protected void i_UserLV_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
if (CpzListView.SelectedDataKey != null && !string.IsNullOrEmpty(CpzListView.SelectedDataKey["id"].ToString()))
{
var cpzId = CpzListView.SelectedDataKey["id"];
var cpzName = ControlValue("tbCpzName", CpzListView.EditItem);
var cpzCode = ControlValue("tbCpzCode", CpzListView.EditItem);
string updateCpzQuery = string.Format(#"update cpz c
set c.cpzname = {0}
and c.code = {1}
where c.id = {2}", cpzName, cpzCode, cpzId);
if (AOneConnectDB.ExecuteNonQuery(updateCpzQuery))
{
AGUI.ShowMessage(MessageType.Success, "CPZ Modified.");
}
}
}
protected void i_UserLV_ItemCreated(object sender, ListViewItemEventArgs e)
{
// must empty
}
}
}
You should write page load method code like this:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
return;
UpdateBinding();
}
In your code edited data lose befor editing code run, because when you click on save button first page load will execute and it bind your list view with old datas(UpdateBinding) then i_UserLV_ItemUpdating will execute. break point will help you undrestand how it work.
Nothing wrong with your code. you miss small thing.
To get data always actual you need to set EnableViewState="false". The main thing is that setting this just for specific input is not enough. This worked for me only after I set page level view state like this.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication8._Default"
EnableViewState="false" %>
i have two tables which stores items and itemsizes, a item will have different sizes. i am trying to display the itemsizes for the item in a dropdownlist with in a datalist. my html is as below
<asp:DataList ID="dlstCartItems" runat="server" RepeatDirection="Horizontal" RepeatColumns="5"
Width="580px" ForeColor="Blue" DataKeys="ItemCode"
onitemdatabound="dlstCartItems_ItemDataBound">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" style="border: Solid 2px #eeeeee;">
<tr>
<td align="left" style="width: 180px;">
<a href="Videos.aspx?vid=<%# Eval("itemid") %>">
<img src="images/Gallery/<%# Eval("imagename") %>" alt="Image" height="120px" width="185px"
style="border: 0;" />
</a>
</td>
</tr>
<tr>
<td style="width: 180px;" align="left">
<table>
<tr>
<td>
Name:
</td>
<td>
<a href="Videos.aspx?vid=<%# Eval("itemid") %>">
<asp:Label ID="lblVideoName" runat="server" Text='<%# Eval("name")%>' ForeColor="#06C"></asp:Label>
</a>
</td>
</tr>
<tr>
<td>
Author:
</td>
<td>
<a href="Videos.aspx?Authorid=<%# Eval("itemid") %>">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("thm") %>' ForeColor="#06C"></asp:Label></a>
</td>
</tr>
<tr>
<td>
Technology:
</td>
<td>
<a href="Videos.aspx?Techid=<%# Eval("itemid") %>">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("itemcode") %>' ForeColor="#06C"></asp:Label></a>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlAvailableSizes" runat="server" >
</asp:DropDownList>
</td>
</tr>
</table>
</ItemTemplate>
<%--<AlternatingItemStyle BackColor="Silver" />--%>
<ItemStyle BackColor="#eeeeee" />
</asp:DataList>
This is my bind method
var query = (from b in db.CR_CartItems
join c in db.CR_CartItems_Sizes on b.ItemCode equals c.ItemCode
join k in db.CR_ScrollingMenus on b.ThemeID equals k.MenuID
where b.status == true
orderby b.updatedat descending
select new
{
itemid = b.Itemid,
imagename = b.galleryimg,
itemcode = b.ItemCode,
thm = k.DisplayName,
name = b.posterName
}).Distinct();
foreach (var q in query)
{
var query1 = from b in db.CR_CartItems_Sizes
join c in db.CR_CartItems on b.ItemCode equals c.ItemCode
where b.ItemCode == q.itemcode
select new
{
b.SizeDesc,
b.ItemCode
};
foreach (DataListItem li in dlstCartItems.Items)
{
DropDownList list = (DropDownList)li.FindControl("ddlAvailableSizes");
list.DataSource = query1;
list.DataTextField = "SizeDesc";
list.DataValueField = "ItemCode";
list.DataBind();
list.Items.Insert(0, "Available Sizes");
}
}
dlstCartItems.DataSource = query;
dlstCartItems.DataBind();
}
i have set up a break point at the foreach loop and checked, it is not entering the loop. any help is appreciated.
You have to handle the DataList.ItemDataBound event:
Assuming you are binding your DataList like: (or similar, using a data source control)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.dl.DataSource = GetDataSource();
this.dl.DataBind();
}
}
Then your ItemDataBound handler would look like:
protected void dl_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var myDropDownList = e.Item.FindControl("YourDropDownListID") as DropDownList;
int currentItemID = int.Parse(this.dl.DataKeys[e.Item.ItemIndex].ToString());
myDropDownList.DataSource = GetDDLDataSource(currentItemID);
myDropDownList.DataBind();
}
}
Finally make sure to register the event in the DataList markup
<asp:DataList ID="dl" runat="server"
onitemdatabound="dl_ItemDataBound"
DataKeyField="Your_Row_ID"
>
I'm sure I've done this before but really cant remember how.
In the ItemDataBound event of a ListView I need to get the actual data value. I cant seem to find it in the ListViewItemEventArgs object that gets passed in.
Thanks
Use the ListViewDataItem in the ItemDataBound event:
protected void yourListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
YourDataSource yourDataSource= (YourDataSource )dataItem.DataItem;
}
}
I think what you're after is the ListViewDataItem.DataItem
protected void Score_ItemDataBound(object sender, Telerik.Web.UI.RadListViewItemEventArgs e)
{
if (e.Item is RadListViewItem)
{
RadListViewDataItem item = e.Item as RadListViewDataItem;
object dataItem = ((System.Data.DataRowView)(((RadListViewDataItem)e.Item).DataItem)).Row.ItemArray[2].ToString();
string raetest = Convert.ToString(dataItem);
}
}
<asp:ListView ID="ContactsListView"
DataSourceID="ContactsDataSource"
ConvertEmptyStringToNull="true"
OnItemDataBound="ContactsListView_ItemDataBound"
runat="server">
<LayoutTemplate>
<table cellpadding="2" width="680px" border="0">
<tr style="background-color: #ADD8E6" runat="server">
<th runat="server">First Name</th>
<th runat="server">Last Name</th>
<th runat="server">E-mail Address</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
<asp:DataPager runat="server" ID="PeopleDataPager" PageSize="12">
<Fields>
<asp:NumericPagerField ButtonCount="10" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #CAEEFF" runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%#Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%#Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="EmailAddressLabel" runat="server" Text='<%#Eval("EmailAddress") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Server side
protected void ContactsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// Display the e-mail address in italics.
Label EmailAddressLabel = (Label)e.Item.FindControl("EmailAddressLabel");
// EmailAddressLabel.Font.Italic = true;
string valueoftheControl = EmailAddressLabel.Text;
/* you have to get the value like this.
If its a dropdown or any other use their
corresponding property to get the value.*/
}
}