Want Checked Item From Listview - c#

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);

Related

How to store information in the view list in the database

How can I save rows created in the list view in my database? How can I access the values ​​in the (list view)? How to save the values ​​created in the view list to the database?
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate runat="server">
<tr class="text-center">
<td class="product-remove"></td>
<td class="image-prod">
<div class="">
<asp:Image ID="Image1" CssClass=" img" ImageUrl='<%# "../img/" + Eval("picture" )%>' runat="server" />
</div>
</td>
<td class="product-name"><%# Eval("namebook") %> </td>
<td id="t_Plural" runat="server" class="price "><%# Eval("Price") %> </td>
<td class="quantity"><%# Eval("titel") %></td>
<td class="col-2">
<asp:Button ID="delete" CssClass="btn btn-outline-danger" CommandArgument='<%# Eval("id")%>' OnClick="delete_Click" runat="server" Text="حذف کالا" />
</td>
<td>
<%-- <input id="quantity2" runat="server" type="number" AutoPostBack="true" oninput="lod_gheymat" onserverclick="lod_gheymat" value="" min="1" max="20" />--%>
<asp:TextBox ID="quantity2" runat="server" CssClass="input-wrap" AutoPostBack="true" OnTextChanged="lod_gheymat" Text="1" min="1" max="20"></asp:TextBox>
</td>
<td >
<div class="row">
<asp:Label ID="lbl_Plural" runat="server" Text="0"></asp:Label> <span class="row"> تومان</span>
</div>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
The way to approach this type of issue and problem is to NOT try and add to the database from the list view.
What you do is get your data (say in a data table).
then send the data table to the list view.
Now, if you want say a "add new row" button?
Add the row to the data table, and then re-bind the list view.
Next up?
You asking how to add this to the database, but is not that where it came form in the first place?
and it is VERY confusing that you asking how to add rows to this LV, but how is the user going to add the picture?
Next up, how is this post getting up-votes? I will assume up-votes are not being messed with? I'll put this issue aside, but something not fitting here.
Ok, so, how to add rows, and how to save such rows back to the database?
You can achieve this goal this way:
First, we assume the LV can now be freely edit. That means using text boxes.
so, we have this markup:
(probably not HUGE important the LV you have, but the "idea" outlined here should work fine).
<style> .borderhide input, textarea {border:none}</style>
<div style="width:70%;padding:20px">
<h2>Fighter Prints</h2>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr style="">
<td><asp:TextBox ID="Fighter" runat="server" Text='<%# Eval("Fighter") %>' TextMode="MultiLine" /></td>
<td><asp:TextBox ID="Engine" runat="server" Text='<%# Eval("Engine") %>' TextMode="MultiLine" Width="200px" /></td>
<td><asp:TextBox ID="Thrust" runat="server" Text='<%# Eval("Thrust") %>' Width="70px" /></td>
<td><asp:TextBox ID="Description" runat="server" Text = '<%#Eval("Description") %>'
TextMode="MultiLine" Width="340px" Rows="5" /></td>
<td>
<asp:Image ID="iPreview" runat="server" Height="68px" Width="149px"
ImageUrl='<%# Eval("ImagePath") %>'/>
</td>
<td><asp:TextBox ID="Qty" runat="server" Text='<%# Eval("Qty") %>' style="width:30px;text-align:right"/></td>
<td><asp:TextBox ID="Price" runat="server" Text='<%# string.Format("{0:c2}",Eval("Price")) %>' style="Width:70px;text-align:right"/></td>
<td><asp:TextBox ID="Total" runat="server" Text='<%# string.Format("{0:c2}",Eval("Total")) %>' style="Width:70px;text-align:right" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server"
class="table table-hover borderhide ">
<tbody>
<tr runat="server" style="" >
<th runat="server">Fighter</th>
<th runat="server">Engine</th>
<th runat="server">Thrust (lbs)</th>
<th runat="server">Description</th>
<th runat="server">Preview</th>
<th runat="server" style="text-align:right">Qty</th>
<th runat="server" style="width:70px;text-align:right">Price</th>
<th runat="server" style="width:70px;text-align:right">Total</th>
</tr>
<tr id="itemPlaceholder" runat="server" />
</tbody>
<tfoot>
<tr>
<td></td><td></td><td></td><td></td><td></td><td></td><td>Total</td>
<td><asp:TextBox ID="MyTotal" runat="server" Text="0" Width="70px" Style="text-align:right"></asp:TextBox></td>
</tr>
</tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
Ok, so the code to load is now this:
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
Session["rstData"] = rstData;
}
else
rstData = Session["rstData"] as DataTable;
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
conn.Open();
rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
rstData.Columns.Add("Total", typeof(decimal),"[Qty] * [Price]");
ListView1.DataSource = rstData;
ListView1.DataBind();
decimal myTotal = 0;
foreach (ListViewItem OneRow in ListView1.Items)
{
TextBox MyPrice = OneRow.FindControl("Total") as TextBox;
myTotal += Decimal.Parse(MyPrice.Text, NumberStyles.Currency);
}
// now update the final total label
TextBox lblTotal = ListView1.FindControl("MyTotal") as TextBox;
lblTotal.Text = string.Format("{0:c2}", myTotal);
}
}
}
And now we have this:
Ok, for the above, note how we added 3 buttons below the LV.
And becuase I wanted "cute" icons in the buttons, I dropped in hteml buttons, not asp.net ones. But, with a "id" and runat=server, they work JUST the same anyway.
So, our 3 buttons are (right after the LV markup)
<div style="float:left">
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-save"></span> &nbspSave
</button>
<button id="cmdUndo" runat="server" class="btn" style="margin-left:10px" onserverclick="cmdUndo_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-retweet"></span> &nbspUn do
</button>
</div>
<div style="float:right">
<button id="cmdAddNew" runat="server" class="btn" onserverclick="cmdAddNew_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-new-window"></span> &nbspAdd New
</button>
</div>
Ok, so of the 3, the un-do button code is easy:
protected void cmdUndo_ServerClick(object sender, EventArgs e)
{
// undo changes - just re-load the lv
LoadGrid();
}
Ok, now the save button. This save button will:
save any new rows, and ALSO save any editing we do. Remember, since we used text boxes, then I can quite much tab around - edit ANY row. If I hit save, then we save all edits AND ALSO any new row added.
So, the save button does this:
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
GridToTable(); // send lv to table
SaveToDatabase();
}
So, now we need the routine to send the LV to the table. That code is this:
void GridToTable()
{
// pull grid rows back to table.
foreach (ListViewItem rRow in ListView1.Items)
{
int RecordPtr = rRow.DataItemIndex;
DataRow OneDataRow;
OneDataRow = rstData.Rows[RecordPtr];
OneDataRow["Fighter"] = ((TextBox)rRow.FindControl("Fighter")).Text;
OneDataRow["Engine"] = ((TextBox)rRow.FindControl("Engine")).Text;
OneDataRow["Thrust"] = ((TextBox)rRow.FindControl("Thrust")).Text;
OneDataRow["Description"] = ((TextBox)rRow.FindControl("Description")).Text;
OneDataRow["Qty"] = ((TextBox)rRow.FindControl("Qty")).Text;
OneDataRow["Price"] = Decimal.Parse(((TextBox)rRow.FindControl("Price")).Text,
NumberStyles.Currency);
}
}
So, the above takes ANY edit - any row you edit, and send changes from LV->rstData.
So, now we need the rstData save all rows, all edits, all additions back to the database, and that code is this:
void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, now that is quite much all we need.
The last button, "add row" is also easy, and looks like this:
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
// user might have done some editing, so, pull LV to table
// just in case
GridToTable();
// add new row to database
DataRow MyNewRow = rstData.NewRow();
// setup some defaults and values for this new row
//MyNewRow["DateCreate"] = DateTime.Now;
rstData.Rows.Add(MyNewRow);
ListView1.DataSource = rstData;
ListView1.DataBind();
}
That is it. So, if I am looking at above LV, and hit add-new, we now have this:
so I can just fill out the information, and then hit save. If I hit un-do, then the row will not be added (nor saved).
Note how we had a min of code to do the save. Note how we did not mess with a boatload of templates (and thus save world poverty).
So, this works really nice, was not a lot of code and the real secrets "idea" here was persisting the rstData. This allows great ease of adding new rows, but MORE important it was very simple then to send the edits back to the database, and that one save command will not only save any editing in the LV, but also will create the new rows in the database for you. So, you can quite much tab around in that lv - almost like excel. So we don't have a huge mess of "edit" buttons, and all that jazz. Just a simple grid of data, and a simple save, or add new button.
Note VERY careful how the GridToTable works. As this shows HOW to grab, and get values from the LV, and that was quite much the "major" part of your question. So, you can grab any row of the LV, but to pull values out of the one row, you have to use "FindControl".
protected void savetodatabase_Click(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl Labelid;
TextBox quantity2;
foreach (ListViewItem rRow in ListView1.Items)
{
itemlist iteml = new itemlist();
quantity2 = (TextBox)rRow.FindControl("quantity2");
Labelid = (System.Web.UI.HtmlControls.HtmlGenericControl)rRow.FindControl("Labelid");
iteml.quantity = quantity2.Text;
iteml.bookid = Convert.ToInt32(Labelid.InnerText) ;
iteml.Date = DateTime.Now;
iteml.userid = Convert.ToInt32(Session["userid"].ToString()) ;
DatabaseContext context = new DatabaseContext();
context.itemlists.Add(iteml);
context.SaveChanges();
}
}

Problems with Radio button in the datalist

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.

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();
}
}
}

How to get Value from DropDownList inside a ListView?

I have a DropDownList inside in ListView..
I wanted to get a data when command clicked.
this is my code..
protected void ListView2_ItemCommand(object sender, ListViewCommandEventArgs e){
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
but it always return null value..
I've googling about 3 hours, and try many function..
but still cant solve this bug..
please help me guys,
UPDATE
here's my aspx page
<asp:DropDownList ID="ShippingComapnyDDL" runat="server" SelectedValue='<%# Eval("ShippingCompany") %>'>
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="FedEx" Value="FedEx"></asp:ListItem>
<asp:ListItem Text="UPS" Value="UPS"></asp:ListItem>
<asp:ListItem Text="Other" Value="Other"></asp:ListItem>
</asp:DropDownList>
DO you have headers set?try
if(e.Item.ItemIndex!=-1)
{
string shipmethod = ((DropDownList)e.Item.FindControl("ShippingComapnyDDL")).SelectedValue;
}
if not working then try
string shipmethod = (e.Item.FindControl("ShippingComapnyDDL") as DropDownList).SelectedValue;
Please try
<%#DataBinder.Eval(Container.DataItem,"ShippingCompany")%>
instead of
<%#Eval("ShippingCompany")%>
For more details:
http://aspadvice.com/blogs/joteke/archive/2008/08/24/Is-_2200_Databinding-methods-such-as-Eval_280029002C00_-XPath_280029002C00_-and-Bind_28002900_-can-only-be-used-in-the-context-of-a-databound-control_2E002200_-causing-you-grief_3F00_.aspx
try this:
DropDownList ddl = (DropDownList)e.Item.FindControl("ShippingComapnyDDL");
if (ddl != null)
{
//code here
}
<asp:ListView ID="lvwCoreConfigureData" runat="server" DataKeyNames="Course_Config_Id" OnItemCommand="lvwCore_Config_ItemCommand" OnItemDataBound="lvwCore_Config_ItemDataBound">
<LayoutTemplate>
<table class="table mobile-stacked mb-0">
<thead>
<tr role="row">
<th style="width: 240px">
<asp:Label runat="server" Text="<%$Lang:Resource.Core_Config_Course %>"></asp:Label>
</th>
</tr>
</thead>
<tbody>
<tr runat="server" id="itemPlaceholder" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr role="row">
<td data-th="Name">
<asp:DropDownList ID="ConfigCourseName" runat="server" AutoPostBack="true" CssClass="form-control" OnSelectedIndexChanged="ConfigCourseName_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
2 . This methos will be provide data binding to dropdown while edit mode
protected void lvwCore_Config_ItemDataBound(Object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item; // load one row item
var CourseId = ((Edulearn.Model.CoreProgramme.CoreProgrammeConfigrationDM)dataItem.DataItem).CourseId; //
DropDownList ConfigCourseName = (e.Item.FindControl("ConfigCourseName") as DropDownList);
ConfigCourseName.DataSource = CoreProgrammeRepository.GetCoreProgrammeCourseList(TimeZoneId, new { Name = "TEST" }); // Get the data to dropdown (all data)
ConfigCourseName.DataTextField = "Name"; // assign here which one need to display
ConfigCourseName.DataValueField = "CourseId"; // assign here which one is the value for database save
ConfigCourseName.DataBind(); // bind the data
ConfigCourseName.SelectedValue = CourseId.ToString(); // Here selected values from database will be added
ConfigCourseName.Items.Insert(0, new ListItem("Please select")); // Default value only for display
}
}

How to get the Id of Checkbox which is inside a Repeater

I have a repeater inside which i put a Checkbox and above rapeater there is a HTML checkbox which is used to Check/Uncheck a Checkbox which is inside repeater using client side javascript.
Here is my Code:
JavaScript for Check/Uncheck:
<script type="text/javascript">
function selectAll() {
for (i = 0; i < document.all.length; i++) {
alert("Working");
if (document.all[i].type == 'checkbox') {
if (document.getElementById(cbSelectAll).Checked = true) {
//document.all[i].Checked = false;
} else {
document.all[i].Checked = true;
}
}
}
}
</script>
HTML Code for Repeater:
<div id="hdPropertyList" runat="server">
<table border="0" cellpadding="0" cellspacing="0" class="navigation" width="100%">
<tr>
<td>
<input type="checkbox" id="cbSelectAll" onchange="selectAll()" />
<asp:Button runat="server" ID="btnContactAll" Text="Contact All" />
</td>
<td id="tdOrderBy" runat="server">
</td>
<td>
<asp:Label ID="lblPage" runat="server" CssClass="pageList"></asp:Label>
</td>
</tr>
</table>
</div>
<div class="boxleft SearchFeaturedlist" style="display: none">
<h2>
Featured Properties</h2>
</div>
<asp:Repeater ID="rptPropertyList" runat="server" EnableViewState="false" OnItemDataBound="rptPropertyList_ItemDataBound"
OnLoad="rptPropertyList_Load">
<ItemTemplate>
<table id="propertyTable" runat="server" enableviewstate="false">
<tr id="tbrLabel" runat="server" enableviewstate="false">
<td id="tbcLabel" colspan="3" runat="server" enableviewstate="false">
</td>
</tr>
<tr id="tbrTitle" runat="server" enableviewstate="false">
<td id="tbcTitle" runat="server" enableviewstate="false">
<asp:CheckBox ID="ChkSelect" runat="server" /><span id="spnSelect" runat="server"></span>
</td>
</tr>
</table>
<div id="divAds" runat="server" visible="false" enableviewstate="false" style="width: 100%;
overflow: hidden">
</div>
</ItemTemplate>
</asp:Repeater>
Please help me in this regards.
Thanks in Advance.
The ID of the repeater will be available through it's ClientID property.
Really, you want to be asking whether you need this at all. Why not place the repeater inside a named div, and then simply find all input elements that have a type of checkbox that reside within it ( getElementsByTagName would help here ).
With a decent js addon library, like mootools or jQuery, you'll be able to use CSS selectors, which will make your task even easier.
Here's mootools example :-
function selectAllOrNone()
{
var myNewValue = $('selectall').innerText == "All" ? "None" : "All";
var myCheckers = $$('input[type=checkbox]');
$('selectall').innerText = myNewValue;
myCheckers.each(
function(e) {
e.checked = (myNewValue == "None");
}
);
}
I got the answer using Jquery. I used only the HTML checkbox to Check Uncheck all the checkbox on my Asp.net page.
<script type="text/javascript">
$(document).ready(function() {
$('td.title_listing :checkbox').change(function() {
$('#cbSelectAll').attr('checked', false);
});
});
function CotactSelected() {
var n = $("td.title_listing input:checked");
alert(n.length);
var s = "";
n.each(function() {
s += $(this).val() + ",";
});
window.location = "/D_ContactSeller.aspx?property=" + s;
alert(s);
}
Thanks to "Paul Alan Tylor" for your guidance.

Categories