Check checkboxlist Items as value in querystring in asp.net - c#

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.

Related

Uncheck item from checkboxList which gets selected with querystring onLoad

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.

Multiple selection from one GridView and display data in another GridView

I am having problem with GridView on row command and stack up the data in another GridView:
private List<DistributionStandardPackingUnitItems> tempDistSPUI
{
get
{
if (ViewState["tempDistSPUI"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["tempDistSPUI"];
}
}
set
{
ViewState["tempDistSPUI"] = value;
}
}
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
//Get selected standard packing name
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
//Get the record from view state
itemList = tempDistSPUI;
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = itemList;
gvFinalised.DataBind();
//Save the last record to view state
this.tempDistSPUI = itemList;
}
Let's say when I first selected a row from gvSPU, it returns an itemList filled with data and display in gvFinalised. What I am trying to do is if I selected another row from gvSPU, the previous records in gvFinalised will still there and stack up another itemList from the secondly selected row instead of wiping up the record previously and display the latest itemList data.
I am using viewState but it does not work.
EDIT
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
//Check if itemList and prodVariantDetail list contains any duplicate records
var Gdupes = itemList.GroupBy(x => new { x.id }).Where(x => x.Skip(1).Any()).ToList();
List<DistributionStandardPackingUnitItems> dupes = Gdupes.SelectMany(x => x).ToList();
prodVariantDetail = itemList.Except(dupes).ToList();
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
foreach (GridViewRow gr in gvFinalised.Rows)
{
//Get the product packaging quantity by productName
string name = gr.Cells[1].Text;
int productQuantity = packBLL.getProductQuantityByName(name, distributionID);
TextBox tb = (TextBox)gr.Cells[5].FindControl("tbQuantity");
if (productQuantity == 0)
{
tb.Text = productQuantity.ToString();
}
else
{
tb.Text = (productQuantity / packagesNeeded).ToString();
}
}
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
private List<string> SelectedVariantDetailIDs
{
get
{
if (ViewState["SelectedVariantDetailIDs"] == null)
{
return new List<string>();
}
else
{
return (List<string>)ViewState["SelectedVariantDetailIDs"];
}
}
set
{
ViewState["SelectedVariantDetailIDs"] = value;
}
}
The problem is the following lines:
//Get the record from view state
itemList = tempDistSPUI;
// here itemList will be replaced
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
First you assign tempDistSPUI from ViewState to itemList, but then you replace itemList at the next line. You need to add the elements returned from packBLL.getAllDistSPUItemByDistributionIDnSPUName to itemList instead of replacing itemList. Here's what I would do using List.AddRange Method:
itemList = tempDistSPUI;
// add the returned elements to itemList
itemList.AddRange(packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname));
UPDATE
To prevent duplication with the previous elements:
itemList = tempDistSPUI;
List<DistributionStandardPackingUnitItems> itemListNew = new List<DistributionStandardPackingUnitItems>();
itemListNew = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
// get all previous IDs in a List<int>
List<int> previousIDs = itemList.Select(x => x.id).ToList();
// filter itemListNew and add the elements to itemList
itemList.AddRange(itemListNew.Where(x => !previousIDs.Contains(x.id));

How do we assign individual lists as gridview columns?

I have performed enormous amount of Google search on this topic but couldn't really find the proper answer to this question. The solution might be simple, but I am a beginner to C# ASP.NET.
I have some code that is taking and storing user inputs from a dropdown list and a textbox into its individual List. I am trying to display both lists in a single gridview as individual columns. For an example, when a user selects a product and type in the quantity and hits the add button, it should display the details in a single row of a gridview. Now I have achieved saving the data into a list but cannot get it to display it in a single row.
Here is my code:
List<string> productIdList = new List<string>();
List<string> productTemp = new List<string>();
List<string> quantityList = new List<string>();
List<string> quantityTemp = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
productTemp = (List<string>)ViewState["productId"];
quantityTemp = (List<string>)ViewState["quantity"];
string str1 = Convert.ToString(productTemp);
string str2 = Convert.ToString(quantityTemp);
if (str1 != "")
{
if (productTemp.Count != 0)
{
foreach (string ids in productTemp)
{
productIdList.Add(ids);
}
}
}
if (str2 != "")
{
if (quantityTemp.Count != 0)
{
foreach (string qtys in quantityTemp)
{
quantityList.Add(qtys);
}
}
}
}
}
protected void btnContinue_Click(object sender, EventArgs e)
{
productIdList.Add(ddlProduct.SelectedValue.ToString());
quantityList.Add(txtQuantity.Text);
ViewState["productId"] = productIdList;
ViewState["quantity"] = quantityList;
txtQuantity.Text = "";
ArrayList testList = new ArrayList();
testList.AddRange(productIdList);
testList.AddRange(quantityList);
grdTest.DataSource = testList;
grdTest.DataBind();
grdProduct.DataSource = productIdList;
grdProduct.DataBind();
grdQuantity.DataSource = quantityList;
grdQuantity.DataBind();
}
}
The gridview currently present are for test purpose to check if data persists after every click of button. grdTest is what I am using for trying to display my list as columns.
Final would be something like this:
Name Qty
----- -----
Name1(list1) 5(list2)
Thanks!
You can use Linq to create List of object with Name and Qty from two lists like below
var temp = productIdList.Zip(quantityList, (n, w) => new { Name = n, Qty = w });
grdTest.DataSource = temp.ToList();
grdTest.DataBind();
Gridview you have to show both name and quantity in one row, if you join name and quantity to a one list it will not display as you expected ( all will show in one column)
we can create new class with Name and Qty as properties and create List of items by iterating though productIdList and quantityList.
Read more about Enumerable.Zip

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

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

gridview checkbox problem asp.net

I am trying to implement a checkbox within gridview,
The job of this checkbox is to verify a record,
When this verify button is pressed, all items with a checked checkbox are inputted into the database
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cbox = ((CheckBox)row.FindControl("Verify"));
if (cbox.Equals(true))
{
String DraftsText = ((TextBox)row.FindControl("numDrafts")).Text;
String TCtext = ((TextBox)row.FindControl("numTC")).Text;
if (row.RowType == DataControlRowType.DataRow)
{
//Header trs = new Header();
// GridView1.Rows[0].FindControl("numTC");
if (TCtext != "" && DraftsText != "")
{
// try
// {
string date = row.Cells[4].Text;
DateTime dateTime = Convert.ToDateTime(date);
string dateFormatted = dateTime.ToString("d-MMM-yy");
string unit = row.Cells[5].Text;
string currency = row.Cells[6].Text;
string totalFC = row.Cells[7].Text;
string totalDC = row.Cells[8].Text;
int d = Convert.ToInt32(DraftsText);
int tc = Convert.ToInt32(TCtext);
hdr = new Header(d, tc, dateFormatted, unit, currency, totalFC, totalDC);
hdr.InsertFCTC(hdr);
}
}
}
}
}
I might be going at this the wrong way but in the if (cbox.Equals(true))
its giving me an exception: Object reference not set to an instance of an object.
Any idea what i can do to solve this?
Many Thanks
This if (cbox.Equals(true)) should be if (cbox.Checked)
Since your cbox is a checkbox object it can't be used to compare, so you have to use the cbox Checked Property, which will return true/false
You receive a NullPointerException because the suggested checkbox wasn't found! Or the direct cast into an instance of type CheckBox doesn't worked as expected.
Change your code to something like this and retry:
CheckBox cbox = ((CheckBox)row.FindControl("Verify"));
if (cbox != null && cbox.Checked)
{
....
}

Categories

Resources