I have a Listview control "lstStudents" and i have added checkboxes inside the List viewControl.I need to add a Select All check box which results in checking all the checkboxes inside the ListView i use the following code but it doesn't work.
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (Control cont in lstStudents.Controls)
{
if (cont.GetType() == typeof(CheckBox))
{
(cont as CheckBox).Checked = true;
}
}
}
I'm using c# windows Forms......
You are talking to the dataitem instead of the control itself
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in lstStudents.Items)
{
item.Checked = chkAll.Checked;
}
}
the Checked property is always accessible on a ListViewItem, visible or not.
lstStudents.Items returns only ListViewItem
so there is no need for an extra reference validation on these items
Try this:
private void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListViewDataItem item in lstStudents.Items)
{
CheckBox cbSelect = item.FindControl("cbSelect") as CheckBox;
if (cbSelect != null)
{
cbSelect.Checked = true;
}
}
}
Assuming your listview definition goes something like this:
<asp:listview runat="server">
<itemtemplate>
<asp:checkbox id="cbSelect" runat="server" />
</itemtemplate>
</asp:listview>
Related
I am making quarantine and I have listView for showcase of all viruses, and I added checkbox to listview in Header Column (I don't know if I can add checkbox in header column). I added separate column with checkboxes.
I want that checkbox in header when it's checked that all checkboxes in viewlist items are checked.
I hope somebody can help. Thanks!
Using a Button Click:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].Checked = true;
}
}
Clicking on the Column Header you can use the listView1_ColumnClick(object sender, ColumnClickEventArgs e) event.
In case you have a separate "Select All" checkbox for selecting all items you can have code like:
private void cbSelectAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListViewItem listViewItem in listView.Items)
{
listViewItem.Checked = cbSelectAll.Checked;
}
}
If you want to check all items by clicking on any of list view item, then you have to subscribe to ItemChecked event of a list view:
private void listView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
foreach (ListViewItem listViewItem in listView.Items)
{
listViewItem.Checked = e.Item.Checked;
}
}
PS: To display checkbox above list items set the CheckBoxes flag to true
In my application i have gridview with edit button. By clicking edit button in gridview the listitem of DropDownList gets replaced by the text that is in gridview these are my dropdown list values
--select--
Roller
Heater
Aspx Code:
<asp:DropDownList ID="ddlvalue" runat="server" Width="175px" AppendDataBoundItems="true">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Roller</asp:ListItem>
<asp:ListItem>Heater</asp:ListItem>
</asp:DropDownList>
CS Code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
ddlValue.SelectedItem.Text = (GridView1.SelectedRow.FindControl("lblValue") as Label).Text;
}
here is what you should do. you care currently changing the text of selected item instead of finding the correct item and selecting it. here is how you should do it
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string value=(GridView1.SelectedRow.FindControl("lblValue") as Label).Text;
try
{
foreach(ListItem li in ddlValue.Items)
{
if(li.Text==value)
{
li.Selected=true;
}
else
{
li.Selected=false;
}
}
}
catch
{
}
}
string value = (GridView1.SelectedRow.FindControl("lblRole") as Label).Text;
try
{
ddlvalue.ClearSelection();
ddlvalue.Items.FindByText(value).Selected = true;
}
catch
{
}
I have a problem regarding TReeview and combo box.
Problem:
I have a Treeview with Parent and Child Nodes.
I have a drop box or a combo box. Whenever I select a value from the combobox it should automatically select the same node in the treeview list.
Please give me suggestions on how to perform this.
This is what I tried so far:
protected void nav_dd_parent_SelectedIndexChanged(object sender, EventArgs e)
{
nav_treeview.selectedvalue = nav_dd_parent.selectedvalue.tostring();
}
But it says that nav_treeview is read only and it can not be assigned any values.
I just tried the following to give you an example:
HTML:
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Dictionary<string, Int32> myList = new Dictionary<string, Int32>();
myList.Add("Text1", 1);
myList.Add("Text2", 2);
myList.Add("Text3", 3);
myList.Add("Text4", 4);
myList.Add("Text5", 5);
foreach (KeyValuePair<string, Int32> s in myList)
{
this.TreeView1.Nodes.Add(new TreeNode(s.Key, s.Value.ToString()));
this.DropDownList1.Items.Add(new ListItem(s.Key, s.Value.ToString()));
}
foreach (TreeNode tn in this.TreeView1.Nodes)
{
tn.ChildNodes.Add(new TreeNode("Hello World"));
tn.Collapse();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.DropDownList1.SelectedItem != null)
{
foreach (TreeNode tn in this.TreeView1.Nodes)
{
if (tn.Value == this.DropDownList1.SelectedItem.Value)
{
tn.Selected = true;
if (tn.ChildNodes.Count > 0)
{
tn.Expand();
}
}
else {
tn.Collapse();
}
}
}
}
Hopefully this is what you needed. Good luck!
You will want to set AutoPostBack on the DropDownList and add an OnSelectedIndexChanged event handler. Or, you could try and write it all in javascript to avoid the post back.
I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?
Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}
I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.
The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)
I have a repeater control with a check box, if I check the box then my delete functionality will delete an item in the underlying table.
When I test the delete functionality on an aspx page with a code behind page, everything works fine. Hooray!
However, when I take the repeater and put it into a User Control, the delete functionality thinks that my repeater control has no items.
Code as below, I've tried to strip out the unnecessary code. I asked this question on the asp.net forums but no-one responded!
asxc:
<%# Control AutoEventWireup="true" Inherits="Moto.Web.UI.UserControls.Messages.MessageListForm" Language="C#" %>
<asp:button id="btnDelete" runat="server" text="Delete" OnClick="btnDelete_Click" ></asp:button>
<asp:Repeater ID="RepeaterMessageList" runat="server" EnableViewState="true" >
<ItemTemplate >
<div class="messageContainer item" >
<div class="messageListLeft">
<div class="messageList">
<asp:Image ID="imgUser" runat="server" CssClass="" />
<asp:CheckBox ID="chkDeleteMe" runat="server" Text="test" />
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Code file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.IO;
namespace Moto.Web.UI.UserControls.Messages
{
public class MessageListForm : Moto.Web.UI.UserControls.UserControl//System.Web.UI.UserControl
{
private string userGUID;
private MembershipUser MembershipUser;
private Moto.Business.UserComponent userComponent;
private Moto.Business.User user;
private Button cmdPrev;
private Button cmdNext;
private Button cmdNewest;
private Button cmdOldest;
private Label lblCurrentPage;
private Label lblMessage;
private HyperLink hypPageRedirect;
private Repeater RepeaterMessageList;
private MessageView DisplayMessages = MessageView.Inbox;//default setting
private Button btnDelete;
private Label lblConfirmDelete;
protected Button btnConfirmDelete;
protected Button btnCancelDelete;
enum MessageView
{
Inbox, //0
Sent //1
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.InitializePage();
}
protected void InitializePage()
{
this.cmdNext = (Button)FindControl("cmdNext");
this.cmdPrev = (Button)FindControl("cmdPrev");
this.cmdOldest = (Button)FindControl("cmdOldest");
this.cmdNewest = (Button)FindControl("cmdNewest");
this.lblCurrentPage = (Label)FindControl("lblCurrentPage");
// this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList");
this.RepeaterMessageList = (Repeater)FindControlRecursive(this, "RepeaterMessageList");
this.hypPageRedirect = (HyperLink)FindControl("hypPageRedirect");
this.lblMessage = (Label)FindControl("lblMessage");
//delete functionality
this.btnDelete = (Button)FindControl("btnDelete");
this.lblConfirmDelete = (Label)FindControl("lblConfirmDelete");
this.btnConfirmDelete = (Button)FindControl("btnConfirmDelete");
this.btnCancelDelete = (Button)FindControl("btnCancelDelete");
//where are we coming from - are we the Logged in user or just a voyeur?
if (Page.User.Identity.IsAuthenticated)
{
this.userComponent = new Moto.Business.UserComponent();
this.MembershipUser = Membership.GetUser();//user logged in
this.userGUID = this.MembershipUser.ProviderUserKey.ToString();//signed in user
this.user = this.userComponent.GetByUserGUID(this.userGUID);
}
else
{
Response.Redirect("~/default.aspx");
}
if (null != this.Page.Request.QueryString["viewing"])
{
//reset the enum value
DisplayMessages = this.Page.Request.QueryString["viewing"].ToLower() == "sent" ? MessageView.Sent : MessageView.Inbox;
CurrentPage = 0;//if it's a redirect then reset the Current Page
}
}
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ItemsGet();//on post back we'll call it elsewhere
}
switch (DisplayMessages)
{
case MessageView.Sent:
this.hypPageRedirect.Text += "Inbox";
this.hypPageRedirect.NavigateUrl += "?viewing=Inbox";
break;
case MessageView.Inbox:
this.hypPageRedirect.Text += "Sent Items";
this.hypPageRedirect.NavigateUrl += "?viewing=Sent";
break;
}
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
ItemsGet();
}
protected void cmdNext_Click(object sender, EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
ItemsGet();
}
protected void cmdNewest_Click(object sender, EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage = 0;
// Reload control
ItemsGet();
}
protected void cmdOldest_Click(object sender, EventArgs e)
{
}
public void RepeaterMessageList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Are we vieing the Inbox or Sent items?
if (DisplayMessages == MessageView.Inbox)
{
.........Do stuff
}
else
{
.........Do stuff
}
}
}
private void ItemsGet()
{
// this.RepeaterMessageList = (Repeater)FindControl("RepeaterMessageList");
this.RepeaterMessageList.ItemDataBound += new RepeaterItemEventHandler(RepeaterMessageList_ItemDataBound);
// Populate the repeater control with the Items DataSet
PagedDataSource objPds = new PagedDataSource();
if (DisplayMessages == MessageView.Inbox)//which table are we getting data from?
{
List<Moto.Business.MessageReceived> messages;
Moto.Business.MessageReceivedComponent messageComponent =
new Moto.Business.MessageReceivedComponent();
messages = messageComponent.GetByReceiverGUID(this.user.UserGUID);
objPds.DataSource = messages;
}
else
{
List<Moto.Business.MessageSent> messages;
Moto.Business.MessageSentComponent messageComponent =
new Moto.Business.MessageSentComponent();
messages = messageComponent.GetBySenderGUID(this.user.UserGUID);
objPds.DataSource = messages; //Items.Tables[0].DefaultView;
}
// Indicate that the data should be paged
objPds.AllowPaging = true;
// Set the number of items you wish to display per page
objPds.PageSize = 25;
// Set the PagedDataSource's current page
objPds.CurrentPageIndex = CurrentPage;
this.lblCurrentPage.Text = "Page " + (CurrentPage + 1).ToString() + " of "
+ objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessary
this.cmdPrev.Enabled = !objPds.IsFirstPage;
this.cmdNext.Enabled = !objPds.IsLastPage;
this.cmdOldest.Enabled = !objPds.IsLastPage;
this.cmdNewest.Enabled = !objPds.IsFirstPage;
this.RepeaterMessageList.DataSource = objPds;
this.RepeaterMessageList.DataBind();
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_messagesCurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_messagesCurrentPage"] = value;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in this.RepeaterMessageList.Items)
{
CheckBox chkDeleteMe = item.FindControl("chkDeleteMe") as CheckBox;
TextBox test = item.FindControl("test") as TextBox;
if (chkDeleteMe.Checked)
{
if (DisplayMessages == MessageView.Inbox)//which table are we getting data from?
{
.........Do stuff
}
else
{
.........Do stuff
}
}
}
// Reload control
ItemsGet();
}
protected Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
}
Any help greatly appreciated!
I think the problem is that when the delete button is clicked the Page_Load is fired again and since its a postback it does not execute the ItemsGet method and hence the repeater does not have the data.
Try putting the ItemsGet method call in the OnPreRender event instead of Page_Load.
Jomit
The Delete event fires but in the fornext...loop the repeater thinks it has no items.
After looping it then calls the ItemsGet() Method which returns all data from the table.
So it binds to the repeater and displays all the items correctly but when repeating through the list of items on postback nothing is found?
Is the delete event definately being fired? What is visible after you have hit the delete button? (e.g. is the table empty or does it still display all the items)
Update:
Comment out the GetItems method and see if the table is empty or not on postback. It sounds like your repeaters viewstate isn't populating the control again or something.
Try to move the InitializePage() method to another place. I donĀ“t know why, but I had the same problem and the problem was when I try to access some controls in the OnInit event. I moved to event OnPreLoad() and works.
I hope to help you...
The PreRender solution also worked in our case, where we had such code in two pages of our application. This was working perfect in .Net 1.1 but however broke when we ported this code to .Net 2.0.
Not sure why it broke without any major changes to codebase.
Thanks for the OnPreRender tip!
-Ghanshyam