I have checkboxList which has autopostback true. I have made it in such way in which, on SelectedIndexChanged it gets redirected to same page with querystrting. Querystring value gets generated with selected items. Something like this
www.abcd.com/product?price=2000|3000|5000
So when page gets load the Checkboxlist items gets selected where its value is 2000,3000,5000 etc. But here I have drawback is that when I uncheck any item then agin first it executes pageLoad event code & there it finds value which is uncheck & gets selected again. In short unchecked items gets selected again.
PageLoadevent(Checkbox Items gets selected with querystring values)
string PageUrl = Request.Url.AbsolutePath;
if (PageUrl.Contains("price")) {
string price = Request.QueryString("price");
string[] priceList = price.Split('|');
foreach (string p in priceList) {
if (priceRange.Items.FindByValue(p + "|") != null) {
priceRange.Items.FindByValue(p + "|").Selected = true;
}
}
}
SelectedIndexChanged(URL created with querystring & redirected)
string pageURL = Request.Url.AbsoluteUri;
string strPrice = Request.QueryString("price").ToString;
if (totalcount > 1) {
foreach (ListItem chk in brandsList.Items) {
if (chk.Selected == true) {
selectedBrands += (chk.Value);
}
}
selectedBrands = selectedBrands.Remove(selectedBrands.Length - 1);
Response.Redirect((Request.Url.AbsolutePath + "?") + "&brand=" + selectedBrands + "&price=" + strPrice);
}
if (!IsPostBack)
{
string price = Request.QueryString["price"];
string[] priceList = price.Split('|');
foreach (string p in priceList)
{
if (chkList.Items.FindByText(p) != null)
{
chkList.Items.FindByText(p).Selected = true;
}
}
}
Enclose logic of checkbox selection into IsPostBack condition in page load event. As above. When your page get postback your selection remain as it.
Related
For the purposes of invoicing, I'm keeping track of timesheet entries that are associated with an invoice by storing the selected timesheets in the browser Session and adding/removing entries to that list as the user updates:
The GridView loads all timesheets for the selected company and then indicates by changing row style and select button text:
private void HighlightInvoiceTimesheets()
{
var timesheets = Session["invoiceTimesheets"] as List<Timesheet>;
var invoiceTotalHours = 0;
foreach (var timesheet in timesheets)
{
var tid = timesheet.Id.ToString();
foreach (GridViewRow row in ItemsGrid.Rows)
{
var btn = row.Cells[ItemsGrid.Columns.Count - 1].Controls[0] as LinkButton;
if (ItemsGrid.DataKeys[row.RowIndex].Values["Id"].ToString() == tid)
{
row.CssClass = "success";
btn.Text = "Remove";
int.TryParse(row.Cells[5].Text, out int timesheetHours);
invoiceTotalHours += timesheetHours;
}
}
}
Session["invoiceTotalHours"] = invoiceTotalHours;
BillableHoursLabel.Text = invoiceTotalHours.ToString();
}
When the user "selects" an item in the GridView, it adds or removes the item from the collection in the Session and updates the GridView accordingly:
protected void ItemsGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
// Get the list of timesheets associated with the invoice.
var list = (Session["invoiceTimesheets"] == null) ? new List<Timesheet>() : Session["invoiceTimesheets"] as List<Timesheet>;
// Get the selected timesheet.
int.TryParse(ItemsGrid.DataKeys[e.NewSelectedIndex].Values["Id"].ToString(), out int timesheetId);
var timesheet = timesheetService.GetClearTimesheet(timesheetId);
// Get the select button to update its text.
var btn = ItemsGrid.Rows[e.NewSelectedIndex].Cells[ItemsGrid.Columns.Count - 1].Controls[0] as LinkButton;
// Get the total hours billable for the invoice based on the total hours of the timesheets.
var invoiceTotalHours = (Session["invoiceTotalHours"] == null) ? 0 : int.Parse(Session["invoiceTotalHours"].ToString());
if (list.Find(x => x.Id == timesheetId) != null)
{
// The list contains the selected item, remove it and indicate removed.
list.Remove(timesheet);
ItemsGrid.Rows[e.NewSelectedIndex].CssClass = "";
btn.Text = "Select";
int.TryParse(Session["invoiceTotalHours"].ToString(), out invoiceTotalHours);
invoiceTotalHours -= timesheet.BillableHours;
}
else
{
// The list doesn't contain the selected item, add it and indicate added.
list.Add(timesheet);
ItemsGrid.Rows[e.NewSelectedIndex].CssClass = "success";
btn.Text = "Remove";
int.TryParse(Session["invoiceTotalHours"].ToString(), out invoiceTotalHours);
invoiceTotalHours += timesheet.BillableHours;
}
BillableHoursLabel.Text = invoiceTotalHours.ToString();
// Update the collection in the session.
Session["invoiceTimesheets"] = list;
}
This works without any errors but I'm very confused why list.Remove(timesheet); doesn't actually update the list in memory.
As a result of this, the collection in the session doesn't get updated and changes made don't reflect on the database.
It's because the timesheet you're trying to remove isn't the same object as the one you get from
var timesheet = timesheetService.GetClearTimesheet(timesheetId);
instead of this:
if (list.Find(x => x.Id == timesheetId) != null)
{
// The list contains the selected item, remove it and indicate removed.
list.Remove(timesheet);
Do this:
var timeSheetSession=list.FirstOrDefault(x => x.Id == timesheetId);
if(timeSheetSession!=null) list.Remove(timeSheetSession);
it's pseudo code, i didn't test it.
I got a problem with wpf ComboBox.
I first added a Textbox as the first item to use it for my filtering propose
I then added about 20 Checkboxes in the Combobox through a Foreach loop.
like this
now when i filter them out (i check if true then Visibility.Collapsed) their trace are still in the Combobox like this
Remember that the items are one by one added to the combobox
like this
DataTable machinesTable = machineModel.GetAllMachines().Tables[0];
List<CheckBox> list = new List<CheckBox>();
foreach (DataRow item in machinesTable.Rows)
{
string ID = item["ID"].ToString();
string manufacture = item["MANUFACTURER"].ToString();
string model = item["MODEL"].ToString();
MachinesComboBox.Items.Add(new CheckBox() { Uid = ID, Content = manufacture + " - " + model });
}
and the filtering system works like this
foreach (object item in MachinesComboBox.Items)
{
if (item is CheckBox)
{
if (((CheckBox)item).Content.ToString().Contains(MachinFilterTextbox.Text) || MachinFilterTextbox.Text=="")
{
((CheckBox)item).Visibility = Visibility.Visible;
}
else
{
((CheckBox)item).Visibility = Visibility.Collapsed;
}
}
}
You should look into the MVVM design pattern but as a quick fix you could set the Visibility of the parent ComboBoxItem container:
foreach (CheckBox item in MachinesComboBox.Items.OfType<CheckBox>())
{
ComboBoxItem container = MachinesComboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
if (item.Content.ToString().Contains(MachinFilterTextbox.Text) || MachinFilterTextbox.Text == "")
{
container.Visibility = Visibility.Visible;
}
else
{
container.Visibility = Visibility.Collapsed;
}
}
I want to mark checkboxlist item selected if it's value found in QueryString. e.g.
www.abcd.com/pproducts.aspx?price=1001-2000|2001-5000|5001-10000.
In this url I am filtering products with 3 different price range. Now I have checkboxlist which contains this prices like below
1001-2000
2001-5000
5001-10000
above-10000
so now I want to it should get selected 1001-2000, 2001-5000, 5001-10000
From below code I am redirecting page & making url
private void priceRange_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedPriceRange = priceRange.SelectedValue.ToString;
foreach (ListItem chk in priceRange.Items) {
if (selectedPriceRange.Contains(chk.Value)) {
chk.Selected = true;
}
}
Response.Redirect((Request.Url.AbsoluteUri) + "?price=" + selectedPriceRange);
}
string price = Request.QueryString["price"];
string[] priceList = price.Split('|');
foreach (string p in priceList)
{
if (chkList.Items.FindByText(p) != null)
{
chkList.Items.FindByText(p).Selected = true;
}
}
Above code will select each checkbox as per the value passed in query sting.
I have a grid view, which contains a dropdownlist and a panel that i want to make invisible and visible by the selected value of the dropdownlist.
The javascript code which works when not used with the gridview is:
function showPannel(panelId,dropdownId ) {
var panel = document.getElementById(panelId);
var dropDown = document.getElementById(dropdownId);
if (dropDown.options[dropDown.selectedIndex].value = 'Diesel Deals') {
panel.className = "visibleDiv";
}
else{
panel.className = "hiddenDiv";
}
}
i'm passing the panelId and dropdownlist id from here:
if (e.Row.RowType == DataControlRowType.DataRow)
{
Panel p = (Panel)e.Row.FindControl("Panel1");
DropDownList t1 = (DropDownList)e.Row.FindControl("DropDownList1");
t1.Attributes.Add("onchange",
string.Format("javascript:showPannel('{0}', '{1}')",p.ClientID, t1.ClientID ));
}
but it is not working. The function is getting called, but its giving undefined when dropDown.options[dropDown.selectedIndex].value is alerted.
I tried to do
Gridview1 = document.getElementById('<%=GridView1.ClientID%>');
var cell = Gridview1.rows[0].cells[2];
var dropdownlist = cell.childNodes[0];
var dropdownSelectedValue = dropdownlist.options[dropdownlist.selectedIndex].value;
alert(dropdownSelectedValue);
but its not working either.
Please help
Thanks
Panel p = (Panel)e.Row.FindControl("Panel1");
DropDownList t1 = (DropDownList)e.Row.FindControl("DropDownList1");
string p_id = GridView1.ClientID + "_" + p.ClientID;
string ddL_id = GridView1.ClientID + "_" + t1.ClientID;
t1.Attributes.Add("onchange",
string.Format("javascript:showPannel('{0}', '{1}')", p_id, ddL_id ));
thanks for the hint about rendering id
I am creating a CheckBoxList in a class file and am using an HTMLTextWriter to render the control.
I'm using the following code to store the selected values in a string:
string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
if (YrChkBox.Items[i].Selected)
{
YrStr += YrChkBox.Items[i].Value + ";";
}
}
I stepped through the code and it doesn't seem to hit the inside of the if statement & the selected value attribute is false every time ... Anyone have an idea of how I can address this?
I populate it using the following:
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
In your ASPX page you've got the list like this:
<asp:CheckBoxList ID="YrChkBox" runat="server"
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />
In your code behind aspx.cs page, you have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Populate the CheckBoxList items only when it's not a postback.
YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
}
}
protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Create the list to store.
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in YrChkBox.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
else
{
// Item is not selected, do something else.
}
}
// Join the string together using the ; delimiter.
String YrStr = String.Join(";", YrStrList.ToArray());
// Write to the page the value.
Response.Write(String.Concat("Selected Items: ", YrStr));
}
Ensure you use the if (!IsPostBack) { } condition because if you load it every page refresh, it's actually destroying the data.
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
check boxlist selected values with seperator
string items = string.Empty;
foreach (ListItem i in CheckBoxList1.Items)
{
if (i.Selected == true)
{
items += i.Text + ",";
}
}
Response.Write("selected items"+ items);
An elegant way to implement this would be to make an extension method, like this:
public static class Extensions
{
public static List<string> GetSelectedItems(this CheckBoxList cbl)
{
var result = new List<string>();
foreach (ListItem item in cbl.Items)
if (item.Selected)
result.Add(item.Value);
return result;
}
}
I can then use something like this to compose a string will all values separated by ';':
string.Join(";", cbl.GetSelectedItems());
// Page.aspx //
// To count checklist item
int a = ChkMonth.Items.Count;
int count = 0;
for (var i = 0; i < a; i++)
{
if (ChkMonth.Items[i].Selected == true)
{
count++;
}
}
// Page.aspx.cs //
// To access checkbox list item's value //
string YrStrList = "";
foreach (ListItem listItem in ChkMonth.Items)
{
if (listItem.Selected)
{
YrStrList = YrStrList + "'" + listItem.Value + "'" + ",";
}
}
sMonthStr = YrStrList.ToString();
// aspx.cs
// Load CheckBoxList selected items into ListBox
int status = 1;
foreach (ListItem s in chklstStates.Items )
{
if (s.Selected == true)
{
if (ListBox1.Items.Count == 0)
{
ListBox1.Items.Add(s.Text);
}
else
{
foreach (ListItem list in ListBox1.Items)
{
if (list.Text == s.Text)
{
status = status * 0;
}
else
{
status = status * 1;
}
}
if (status == 0)
{ }
else
{
ListBox1.Items.Add(s.Text);
}
status = 1;
}
}
}
}